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
    Sep 2011
    Location
    UK, South Wales, Newport
    Posts
    21
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Program not running in order

    i noticed the majority of the time when i practice coding javascript and run it, it never runs in the order i want it to. WHY?!

    like for example, if i want something to happen ONLY WHEN A BUTTON IS CLICKED, it would instead happen on page load :S
    its soooo frustrating

    heres one of my practice code which illustrates this problem.
    This code is suppose the stretch a div only wen it is clicked on.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    
    </head>
    
    <body>
        <div id="mybutton" style="height:50px; width:50px; background-color:#C00;"></div>
    </body>
    <script type="text/javascript">
    	var left = 0;
    
    	
    var funct = function () {
    	//alert("Thank you for clicking me");
    	left +=10;
    	b.style.height = left + 'px';
    	if(left < 100) {
    		var id = setTimeout(funct, 10);
    	}
    }
    
    	var b = document.getElementById("mybutton");
    	b.onclick = funct();
    </script>
    </html>

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    726
    Thanks
    35
    Thanked 132 Times in 123 Posts
    b.onclick = funct()

    When you include the parens () the function is called immediately,
    and onclick is assigned the return value of the function.

    funct does not return any value, so future clicks do nothing.

    try b.onclick = funct;

    Now the funct will be called only when the button is clicked
    Last edited by mrhoo; 10-27-2011 at 05:45 PM. Reason: spelling

  • Users who have thanked mrhoo for this post:

    samz (10-27-2011)

  • #3
    New Coder
    Join Date
    Sep 2011
    Location
    UK, South Wales, Newport
    Posts
    21
    Thanks
    8
    Thanked 0 Times in 0 Posts
    omg i love you so much!!!!!


  •  

    Posting Permissions

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