-4

I have a declared function in my code. I want to call this function whenever I click on an item. When I bind it to this item, it gets executed immediately, and the on click event does not trigger.

However, when I declare the function in the on click binding, it works fine.

I want to declare the function somewhere else first, and then call it when the click event happens

function test2() {
  alert('test2');
}

$('body').on('click', '#test1', function() { alert('test1'); });
$('body').on('click', '#test2', test2());

https://jsfiddle.net/ag66r950/

JREN
  • 3,572
  • 3
  • 27
  • 45
  • 1
    You're binding to the return value of `test2` (which is `undefined`). You need to just use `$('body').on('click', '#test2', test2);`. – James Thorpe Mar 09 '16 at 12:24

1 Answers1

3
$('body').on('click', '#test1', function() { alert('test1'); });

This is passing function handle as parameter, not the function result itself

while

$('body').on('click', '#test2', test2());

This is passing result of function execution as a parameter not the function itself.

You need to pass the handle of funciton itself in the event handler

$('body').on('click', '#test2', test2);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94