...

View Full Version : javascript scoping...



Konos5
12-04-2008, 01:14 AM
Hello everyone!

I have some lines of code that actually produce a rolling text from one side of the screen to the other!

Here is the code:


<html>
<head>
<title>Animation1</title>
<style>
#para1 {position: absolute;
color : red;
font-size : 40pt}
</style>
<script language="javascript">
var x = 20, xshift = 1;
function move(elementId) {

x = x + xshift;
elementId.style.left = x;
if (x > 150) {
xshift = -1;
elementId.innerHTML = "Goodbye!";
elementId.style.color = "blue";
}
if (x < 20 ) {
xshift = 1;
elementId.innerHTML = "Hello!";
elementId.style.color = "red";
}
}
</script>
</head>
<body onLoad="intervalId = setInterval('move(para1)',10)"
onClick="clearInterval(intervalId)">
<p id="para1" >
Hello!
</p>
</body>
</html>

The problem comes in everytime the function is called!
I believe that instead of x incrementing by one everytime the function is called, it should permanently stay 21 and do nothing no matter what!
I mean, why javascript prefers to read x's previous value and doesn't just look on its global variables like it does on the "xshift" variable??


Any help would be really appreciated!
Thanks in advance!

abduraooft
12-04-2008, 01:02 PM
Get a copy of firebug (http://www.getfirebug.com/) (which is a great addon for firefox), and try to debug the errors in your script.

Konos5
12-06-2008, 11:54 PM
Did you even read my post?

-The script works perfect! - I just cannot understand how does it work!

abduraooft
12-07-2008, 08:54 AM
Yes, and indeed executed your code in my FF, which had given a lot of errors. And that's why I recommended you to inspect your code by firebug. Anyway, try this one

<!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" dir="ltr" lang="en">

<head>
<title>Animation1</title>
<style>
#para1 {position: absolute;
color : red;
font-size : 40pt;
border:1px solid red;
}
</style>
<script type="text/javascript">
var x = 20, xshift = 1;

function move(id) {
//alert(id);
obj=document.getElementById(id);
x = x + xshift;
obj.style.left = x+'px';
if (x > 150) {
xshift = -1;
obj.innerHTML = "Goodbye!";
obj.style.color = "blue";
}
if (x < 20 ) {
xshift = 1;
obj.innerHTML = "Hello!";
obj.style.color = "red";
}
}
window.onload=function (){
intervalId = setInterval("move('para1')",10)
}
window.onclick=function(){
clearInterval(intervalId);
}
</script>
</head>
<body >
<p id="para1" >
Hello!
</p>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum