2

A simple quick question I simply cannot figure out the answer although I went through a lot of questions here on stackoverflow. I am a newbie, so your patience is appreciated!

Here it goes: I have a function declared (hopefully) like this:

function test(parameter) {
$(parameter).trigger("click");
};

And then I want to call this function when clicked on something, like this:

$("#buttonOne").on("click", test("#correctParameter"));

Now, the issue was the function was actually executed right on the pageload and then didn't work when clicking on the #buttonOne. I read on w3school that

Function expressions will execute automatically if the expression is followed by ().<

And the truth is when I didn't use any parameter it worked only on clicking:

function test() {
$("#correctParameter").trigger("click");
};
$("#buttonOne").on("click", test);

But I have to use the parameter option so I could call on this function other times and giving it different parameter each time. Could you help me solve this?

  • It's a common issue, and they'll be a duplicate with more detail - but essentially, you need to wrap it in `function() {}` (add an inline-anonymous-function) : `$("#buttonOne").on("click", function() { test("#correctParameter") });` – freedomn-m May 12 '20 at 13:45

2 Answers2

1

You should call test in a function as follows:

$("#buttonOne").on("click", function(){
     test("#correctParameter")
});

Here is an example:

function test(parameter) {
     $(parameter).trigger("click");
};
$("#buttonOne").on("click", function(){
     test("#correctParameter")
});
$('#correctParameter').on('click', function(){
     console.log("correctParameter clicked")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="buttonOne">Click</button>
<button type="button" id="correctParameter">Other</button>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • That is brilliant (and the comment below basically saying the same as well). Thank you so much! And sorry I didn't find the duplicate, I really tried to look through loads of questions, but somehow didn't find that one. Works like a charm now :) – Dan Špruček May 12 '20 at 14:10
  • You are welcome! It is a better practice to write your code in a ``function`` instead of calling it directly inside the listener as you did, especially when passing parameters otherwise it will be called directly. – Majed Badawi May 12 '20 at 14:13
0

Javascript allow you to define you callback as anonymous functions and inside it trigger your function call, something like this:

function test(parameter) {
  $(parameter).trigger("click");
};

$("#buttonOne").on("click",function() {
  test('"#correctParameter"');
});
ROOT
  • 11,363
  • 5
  • 30
  • 45