Reputation: 721
Everytime I run this code , witjout clicking the 2 divs , the function doSomething and doSomething2 get called. Can somebody explain the reason please.
function doSomething2(){
console.log("div 1 clicked");
}
//var element1=document.getElementById('div_1');
//var element2=document.getElementById('div_2');
//element1.addEventListener('click',doSomething2,false);
//element2.addEventListener('click',doSomething,true);
$("#div_1").click(doSomething2());
$("#div_2").click(doSomething());
function doSomething(){
console.log("div2 clicked");
}
Upvotes: 0
Views: 68
Reputation: 30330
You should use this instead:
$("#div_1").click(doSomething2);
$("#div_2").click(doSomething);
$(...).click(doSomething)
means "call the function doSomething
when a click event happens in the future"
$(...).click(doSomething())
means "call the function doSomething
now, then use its return value as the action to take when a click event happens in the future."
Upvotes: 0
Reputation: 67207
You are calling the function
instead of passing its reference
.
Try this,
$("#div_1").click(doSomething2);
$("#div_2").click(doSomething);
Fiddle : DEMO
Upvotes: 1
Reputation: 388316
You are invoking the function by appending ()
at the end. To the click()
method you need to pass the handler function references as given below
$("#div_1").click(doSomething2);
$("#div_2").click(doSomething);
Upvotes: 1