Dan Špruček
Dan Špruček

Reputation: 23

Function should execute on click, but does automatically at the loading

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?

Upvotes: 2

Views: 38

Answers (2)

ROOT
ROOT

Reputation: 11622

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"');
});

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28434

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>

Upvotes: 1

Related Questions