javascriptjqueryevent-listenerjquery-eventsjquery-click-event

jQuery .click() function called automatically


I have an event listener set up on a button using jQuery, and for some reason the function within the click listener is called without the button being clicked. I know that usually functions are anonymous in listeners, but it won't work as an anonymous function. The function I am calling also has to accept parameters, which is why I don't think I can just call a reference to the function. Any ideas on how I can fix the problem of the function getting called without a click even registered and still pass the necessary parameters to the function?

$('#keep-both').click(keepBothFiles(file, progress, audioSrc));

calls this function

function keepBothFiles(file, progress, audioSrc) {
    ...
    ...
}

Solution

  • You're referencing the function incorrectly. Try this instead:

    $('#keep-both').click(function(){
      keepBothFiles(file, progress, audioSrc);
    });
    

    Whenever you use the syntax funcName(), the () tell the interpreter to immediately invoke the function. The .click method requires that you pass it a reference to a function. Function references are passed by name only. You could also do:

    $('#keep-both').click(keepBothFiles);
    

    But you can't pass it your other arguments. It's given an event object by default