View Full Version : dynamic divs & onclick

11-10-2012, 11: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"

var newdiv;
for(var i=0;i<Amount*2;i++) {
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();


function divClick() {

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

11-10-2012, 11: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;

11-11-2012, 03: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() {
var a, b;

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

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