Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-27-2011, 02:01 PM   PM User | #1
samz
New Coder

 
Join Date: Sep 2011
Location: UK, South Wales, Newport
Posts: 21
Thanks: 8
Thanked 0 Times in 0 Posts
samz is an unknown quantity at this point
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>
samz is offline   Reply With Quote
Old 10-27-2011, 02:54 PM   PM User | #2
mrhoo
Regular Coder

 
Join Date: Mar 2006
Posts: 708
Thanks: 30
Thanked 127 Times in 118 Posts
mrhoo will become famous soon enoughmrhoo will become famous soon enough
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
mrhoo is offline   Reply With Quote
Users who have thanked mrhoo for this post:
samz (10-27-2011)
Old 10-27-2011, 03:23 PM   PM User | #3
samz
New Coder

 
Join Date: Sep 2011
Location: UK, South Wales, Newport
Posts: 21
Thanks: 8
Thanked 0 Times in 0 Posts
samz is an unknown quantity at this point
omg i love you so much!!!!!
samz is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:48 PM.


Advertisement
Log in to turn off these ads.