0

I feel like this is one of those problems you only run into after too little sleep or too many coffees...

I have an element

<a id="blah" href="#">somethinghere.com</a>

I define a function

function test(){
    alert('hi');
};

I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):

$('#blah').on('click', test());

and load the page, and the handler executes immediately - without any clicks.

However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :

$('#blah').on('click', function(){
    alert('hi');
});

it works fine

Doing both (https://jsfiddle.net/8r1rcfuw/39/):

$('#blah').on('click', function(){
    test();
});


function test(){
    alert('hi');
}

seems to work fine - but seems a little redundant.

This feels like something I've done 1000 times before - what gives?

1
  • 2
    $('#blah').on('click', test()); ==> $('#blah').on('click', test); Remove invocation. Commented Aug 31, 2016 at 9:37

3 Answers 3

2

The event handler has to be a function, and you are passing the result of a function to it:

$('#blah').on('click', test());

is the same as:

$('#blah').on('click', undefined); //As your funcion doesn't return anything

Think of it as a function is a value, you can do:

var myFunction = function() {
    alert("Hi");
}

or

function myFunction() {
    alert("hi");
}

And then:

$('#blah').on('click', myFunction); //Without invocation!

or using an anonymous function:

$('#blah').on('click', function() {
    alert("Hi");
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use object of function :

var temp=function test() {
  alert('hi');
}
$('#blah').on('click', temp);

Comments

0

Try :

$('#blah').on('click', test); // your function name only

Updated Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.