ALBI
ALBI

Reputation: 721

Function getting called without click

Everytime I run this code , witjout clicking the 2 divs , the function doSomething and doSomething2 get called. Can somebody explain the reason please.

http://jsfiddle.net/JuKmM/5/

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

Answers (3)

joews
joews

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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

Arun P Johny
Arun P Johny

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

Related Questions