Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    33
    Thanks
    18
    Thanked 0 Times in 0 Posts

    dynamic divs & onclick

    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:
    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?

  • #2
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    Code:
    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

    Code:
    newdiv.onclick = divClick;

  • #3
    New Coder
    Join Date
    Jul 2012
    Posts
    33
    Thanks
    18
    Thanked 0 Times in 0 Posts
    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:
    Code:
    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?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •