Search code examples
javascriptfunctionargumentsexecuteargs

Javascript executes function immediately when passing arguments, undesired


When I run the code:

 $(".pro-tip-1").mouseover(activateProTip(1));

It calls the function activateProTip right away. It doesn't wait for the mouseover to be a true scenario.

Now if I take out the argument (1) being passed, it runs as intended. It waits for mouseover to be true then it calls the function. This is what I want, however I also want to pass an argument.

 $(".pro-tip-1").mouseover(activateProTip);

The problem is I can't seem to pass an argument and have it run as intended, but I want to be able to pass an argument.

I am completely new to Javascript if that isn't already obvious so please keep your code in response simple to follow, thanks in advance!


Solution

  • This is expected, the required argument is a function. If you instead pass a statement, it will be interpreted immediately (potentially you could have called a function which actually returns a function that you want to call on mouseover!). You can instead write a function that will then call activateProTip with the argument.

    $(".pro-tip-1").mouseover(() => activateProTip(1));