tags:

views:

93

answers:

4

All jQuery examples I see has in-line functions.

If the function is pretty long, or if the function is reusable, I may want to separate the function.

For example, how can I turn this

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

into something like this

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

function ElementClicked(???){
  ???.addCss('clicked');
}

Thanks!

+2  A: 

It's just an expression; you pass it just like you'd pass (x + 1) or whatever. Give it a name in your function and you're good to go:

function elementClicked(banana) {
    banana.addClass('clicked');
}
Pointy
lol @ banana :)
echo
A: 
$('#myElement').click(function(){
  ElementClicked($(this)); 
})

function ElementClicked(el){
  el.addCss('clicked');
}
codemeit
+9  A: 

This won't work:

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

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

You'll need to pass a function to a click event, like so:

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

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

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

As you will notice though, this inside the function that is bound to the event will be the clicked element. So instead of making a function wrapper that calls a function passing the element, you can just abbreviate it like so:

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

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

Notice that the function is passed to click() like a variable instead of being executed immediately, because there are no brackets () following it.

And BTW, you probably mean addClass instead of addCss.

deceze
Best answer! Thank you!
A: 

it is better to seperate between

document.elementByID("div1")

$("#div1")

so I prefer to attatch 'j'

jElement = $("#div1")

element = document.elementByID("div1")

sunglim
I prefer to use '$': `var $div = $('div')`. But to each his own. :)
deceze