Aximili
Aximili

Reputation: 29454

jQuery: How do you pass $(this) as function parameter?

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!

Upvotes: 2

Views: 468

Answers (4)

Sungguk Lim
Sungguk Lim

Reputation: 6218

it is better to seperate between

document.elementByID("div1")

$("#div1")

so I prefer to attatch 'j'

jElement = $("#div1")

element = document.elementByID("div1")

Upvotes: 0

deceze
deceze

Reputation: 522025

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.

Upvotes: 10

Ray Lu
Ray Lu

Reputation: 26648

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

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

Upvotes: 0

Pointy
Pointy

Reputation: 413712

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

Upvotes: 2

Related Questions