2

couldn't find a specific answer.

If I create a jQuery function, call it "doMobile" per say, and I want it to use a function inside of it if so, what do I do?

This is what I am trying to do:

$.fn.doMobile = function(somefunctioninside) {
  if ( $('.mobile').is(':visible') )
     somefunctioninside();
};

$('.menu').doMobile(function() {
  $(this).css('background-color', 'red');
});

When I it like that though, $(this) - $('.menu) doesn't becomes red.

matt4692
  • 120
  • 7
  • @Cerbrus, the question you marked as duplicated is not the good one. The linked question doesn't use jQuery, which is crucial here since the OP want to use `this` as an HTML element. Im sure there is a duplicated somewhere, but it isn't this one (or there is a better one). – Karl-André Gagnon Jun 25 '14 at 12:55
  • The question is about how to call `somefunctioninside`. The linked question explains exactly that. – Cerbrus Jun 25 '14 at 12:58
  • @Cerbrus I agreed, but the answer will not solve the OP problem. He will, after reading it, ask "How to make `this` the HTML element?" – Karl-André Gagnon Jun 25 '14 at 13:00
  • It does answer the question the OP is asking here, however. – Cerbrus Jun 25 '14 at 13:02
  • @Cerbrus hence why should suggest the OP to modify his question before closing it because you know the linked answer *answer* the question but his code will not work... – Karl-André Gagnon Jun 25 '14 at 13:07
  • 1
    I don't think the question will be reopened matt, so here your answer. In your case, you want to use this : `this.each(somefunctioninside)`, but you could also use `somefunctioninside.call(this);`. The second one is different though, `this` will not be an HTML element, but a jQuery object, so don't need to wrap it inside a `$()`. – Karl-André Gagnon Jun 25 '14 at 13:13
  • @Karl-AndréGagnon this.each(somefunctioninside) is exactly what I needed. Thanks! – matt4692 Jun 25 '14 at 13:27

1 Answers1

0

Try this

$.fn.doMobile = function (someFunction) {
    someFunction.call(this);
};

$('.menu').doMobile(test);

function test() {
   this.css('background-color', 'green');
    alert("came");
}

pass this reference . @Karl-AndréGagnon told like this way

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26