-1

I'm trying to run a function on .change() and .click() events with different arguments passed to that function. Function foo runs two times automatically on page load (once for each event). On top of that .change() and .click() events don't do anything when I'm trying to invoke them.

$(document).ready(function(){
    function foo(bar){
        alert("This function runs 2 times on page load");
    }

    $("#some-select").change(foo(false));

    $("#some-button").click(foo(true));
});

I expect foo function not to run automatically on page load.

Jaruzel
  • 99
  • 1
  • 7

2 Answers2

1

Have you tried this:

$(document).ready(function(){
    function foo(bar){
        alert("This function runs 2 times on page load");
    }

    $("#some-select").change(foo.bind(null, false));

    $("#some-button").click(foo.bind(null, true));
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • That worked, thank you! Could you elaborate on why this works and my code didn't work? – Jaruzel Dec 12 '17 at 02:01
  • 1
    @Jaruzel `.bind` lets you preset the value for the `this` keyword and the arguments. Your code `.change(foo(false))` executes the function `foo` immediately instead of passing the function as argument. – Derek 朕會功夫 Dec 12 '17 at 02:02
0

I am able to reproduce the problem, but wrapping the call in a function seems to correct it for me.

$(document).ready(function(){
  function foo(bar){
    if(bar){
      console.log('bar is truthy, and somebutton was clicked');
    } else {
      console.log('bar is falsy, and someselect was changed');
    }
    console.log("This function runs 2 times on page load");
  }

  $("#some-select").change(function(){foo(false)})
  $("#some-button").click(function(){foo(true)});

});

My codepen

Jace
  • 144
  • 1
  • 9