...

View Full Version : dynamic divs & onclick



coffeecup
11-10-2012, 10:21 PM
Hey! very basic question in regards of divs & onclick function:

whenever the function init(Amount) is triggered, it should create divs with an onclick function.

now the onclick function for every div is already triggered the moment init(Amount) is performed (so the alert would pop up once for every div).

why is that? :/

issued part of the code:

function init(Amount)
{
var gameDeck = [
"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"
]
gameDeck.shuffle();

var newdiv;
for(var i=0;i<Amount*2;i++) {
newdiv=document.createElement("div");
newdiv.setAttribute("style","float: left; margin: 10px;");
newdiv.style.width = '65px';
newdiv.style.height = '65px';
newdiv.style.border = '1px solid red';
newdiv.id = gameDeck[i];
newdiv.onclick = divClick();
document.getElementById('playfield').appendChild(newdiv);

}
}

function divClick() {
alert("Clicked");
}


if I replace
newdiv.onclick = divClick();
with
newdiv.onclick = function() {alert("Clicked");};
it actually works... why? :confused:

minder
11-10-2012, 10:37 PM
newdiv.onclick = divClick();

is actually running the function when the above line is executed.

What you really want to do is just assign a reference to the function to the onclick event handler, not actually run it.

So the above line should be just


newdiv.onclick = divClick;

coffeecup
11-11-2012, 02:09 AM
thanks alot :)

another beginners question:
I have a click event on every div and I want to store the IDs which have been clicked (to be exact, I only need the current ID and the previous clicked ID).

it sounds easy enough I'm however too stupid to get it work for some reason
say I want to store the previous clicked id in variable a, the current one in b:


var clicks=0;

function divClick() {
clicks++;
var a, b;

if (clicks % 2 == 0)
{
a=this.id;
checkIDs(a, b);
} else {
b=this.id;
}
}

checkIDs never gets the correct value of b (undefined) :/

is there a better approach for that?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum