Comedy King
Comedy King

Reputation: 13

Jquery, the on click is triggered before even clicking on the button

I am new to jquery and I wrote a method like

function method(mess){
   alert('Hello '+mess);
}
$('#button').click(method('world'));

But every time I refresh the page it is being executed without even being clicked. Am I doing something wrong?

Upvotes: 1

Views: 81

Answers (2)

deepakchethan
deepakchethan

Reputation: 5600

Try something like

function method(mess){
   alert('Hello '+mess);
}
$('#button').click(function(){
     method('world')
});

Your code is behaving that way because you are calling the function method('world') without listening for the click event.

You can see the difference between them on JSfiddle.

Upvotes: 0

Dekel
Dekel

Reputation: 62666

You are not using this correctly.

When you wrote $('#button').click what you actually did was triggering the click event on that element, and regardless - you called the method('world') function.

This is how it should look:

function method(mess){
   alert('Hello '+mess);
}

$('#button').on('click', function() { method('world') });

Upvotes: 3

Related Questions