JQuery: How do you pass $ (this) as a parameter to a function?

All the jQuery examples that I see have built-in functions.

If the function is quite long or the function is reused, I can separate the function.

For example, how can I enable this

$('#myElement').click(function(){ $(this).addCss('clicked'); }) 

into something like that

 $('#myElement').click(ElementClicked($(this)) function ElementClicked(???){ ???.addCss('clicked'); } 

Thanks!

+2
jquery
source share
4 answers

This will not work:

 $('#myElement').click(ElementClicked($(this))); 

Executes the ElementClicked() function with what this at the time of writing, and binds the return value of ElementClicked() to the click event. Which is nothing in this case.

You need to pass the function to the click event, for example:

 $('#myElement').click(function () { ElementClicked($(this)); }); 

This makes a (n anonymous) function that will be bound to the click event, and the function calls ElementClicked() at startup, passing this . The ElementClicked function can be defined as:

 function ElementClicked(elem) { elem.addClass('clicked'); } 

As you noticed, this inside the function bound to the event will be a click of the element. Therefore, instead of creating a functional shell that calls the function that passes the element, you can simply shorten it as follows:

 $('#myElement').click(ElementClicked); function ElementClicked() { $(this).addClass('clicked'); } 

Note that the function is passed to click() as a variable instead of being executed immediately, since there are no brackets () after it.

And BTW, you probably mean addClass instead of addCss .

+10
source share

It is just an expression; you pass it the same way you would pass (x + 1) or something else. Give it a name in your function and you will go well:

 function elementClicked(banana) { banana.addClass('clicked'); } 
+2
source share
 $('#myElement').click(function(){ ElementClicked($(this)); }) function ElementClicked(el){ el.addCss('clicked'); } 
0
source share

better to separate between

document.elementByID ("div1")

$ ("# div1")

so I prefer to set 'j'

jElement = $ ("# div1")

element = document.elementByID ("div1")

0
source share

All Articles