Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Why) does jQuery .click() require a callback function?

I have the following jQuery code:

function next() {
    //some code here
}

function previous() {
    //some code here
}

$("#next").click(function(){
    next();
});

$("#previous").click(function(){
    previous();
});

This works, but this doesn't:

$("#next").click(next());

$("#previous").click(previous());

Why is this happening? Is there a problem in my code, or is this just a thing with jQuery? Note: #next and #previous refer to two buttons in my html file.

like image 710
Rohan Khajuria Avatar asked Sep 20 '26 06:09

Rohan Khajuria


1 Answers

The callback should be a reference to the function.

Why $("#next").click(next()); doesn't work?

func() is a function call and not a reference, which is why it is called immediately.


This,

$("#next").click(function(){
    next();
});

is a preferable way in case you need to pass arguments.

Else,

$("#next").click(next) //notice just the signature without ()
like image 135
Shaunak D Avatar answered Sep 22 '26 18:09

Shaunak D