0

I have a dynamic HTML element and I want to attach a function to the event handler.

drilldownTextInput = $("<input type='text' class='drilldown-search' data-drilldown-options='" + drilldownOptions + "' />");
drilldownTextInput.on('click', showOptions());

function showOptions() {
    console.log("Working.");
}

The problem is that on page load the showOptions() function is called immediately and not on the click event.

If I do this, the event works as expected - only on click.

drilldownTextInput = $("<input type='text' class='drilldown-search' data-drilldown-options='" + drilldownOptions + "' />");
drilldownTextInput.on('click', function() {
    console.log("Only appears on click...");
});

What is the difference between the two and how can I invoke a function in order to keep things DRY?

sergserg
  • 21,716
  • 41
  • 129
  • 182
  • If you have `foo(bar())`, then `bar` is called first and its returned value is passed to `foo`. All arguments are evaluated first. – Felix Kling Feb 23 '14 at 01:58

2 Answers2

1

() calls a function, you should just pass the function without executing it otherwise the returned value of the function is set as the handler.

drilldownTextInput.on('click', showOptions);
Ram
  • 143,282
  • 16
  • 168
  • 197
1

Try the following:

drilldownTextInput.on('click', showOptions);

instead of :

drilldownTextInput.on('click', showOptions());

Reference

ltalhouarne
  • 4,586
  • 2
  • 22
  • 31