Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a handler function on event

Tags:

html

jquery

I believe it is possible to call a function in an event handler, just like this:

$([selector]).[event](function(){
    handlerFunction();
});

Is there a way of doing this in a more compact way? like this:

$([selector]).[event](handlerFunction());

In any case, how do you pass to handlerFunction() the element in which you're calling the event handler? Is it done implicitly? Is it needed a parameter both in the calling and function? I got an unique handler function which behaves differently depending on the item that calls it and I don't know how to pass that info and even if this is correct.

like image 690
Kaplan Avatar asked Apr 11 '26 03:04

Kaplan


2 Answers

$([selector]).[event](handlerFunction);

The element that triggered the event gets passed to handlerFunction via the this keyword:

function handlerFunction() {
    $(this).hide();
}

In this example, handlerFunction would hide the element that triggered the action. Notice that this is the DOM element, $(this) the jQuery equivalent.

like image 52
Niko Avatar answered Apr 12 '26 17:04

Niko


You can pass the handlerFunction as reference, like this:

$([selector]).[event](handlerFunction);

If you use handlerFunction(), the function will be called, and the return value will be passed to the event handler

like image 44
Ortiga Avatar answered Apr 12 '26 18:04

Ortiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!