2

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!

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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');
}

Comments

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

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

Comments

0

it is better to seperate between

document.elementByID("div1")

$("#div1")

so I prefer to attatch 'j'

jElement = $("#div1")

element = document.elementByID("div1")

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.