1

I have a function that opens dialog windows. When the user clicks on the sign up button the sign up dialog should open. However, the dialog opens as soon as the page loads. If I use an anonymous function to handle the event it works fine, but I want to reuse the openDialog function for other dialogs (login, etc) so I don't want it to be anonymous.

var ready;
ready = function () {
    $('.js-join-button').on('click', openDialog(event, signUp));

    function openDialog(event, dialogType) {
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
        dialogType.dialog('open');
    }
...
}
$(document).ready(ready);
Ben Davidow
  • 1,175
  • 5
  • 23
  • 51
  • 1
    possible duplicate of [Why does click event handler fire immediately upon page load?](http://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load) – Felix Kling Apr 01 '14 at 02:01

1 Answers1

5

You need to wrap your function in an anonymous function. Your code will run through and simply trigger the function otherwise.

$('.js-join-button').on('click', function() {
    openDialog(event, signUp)
});

Now, for example, if your function did not take any parameters, you could do

 $('.js-join-button').on('click', openDialog);

This passes a reference to the function. With the () it triggers the function. Without, it's a function reference.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • My second example is not an anonymous function. It's a function reference as I said. – Sterling Archer Apr 01 '14 at 01:54
  • Thank you. :) Still, "trigger" has a very specific meaning in JavaScript, and you use it for two different concepts, neither of which corresponds to the standard meaning of the word (which relates to events, like in `$('#foo').trigger('click')` - as OP has in the title). The first would be better as "supply" or "provide"; the second, "invokes the function". – Amadan Apr 01 '14 at 01:55
  • Well, in that example `trigger` is a jQuery method. JS doesn't have a "set definition" for the word trigger. It can be interpreted in a specific way, but it can also be used as a synonym for invoke, or provide. – Sterling Archer Apr 01 '14 at 01:58
  • Not a "set definition", but we all "know" what we're talking about: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events . Most people think "stack" and "heap" mean the same thing, but programmers keep them strictly separate for a purpose: clear communication. – Amadan Apr 01 '14 at 02:00