PDA

View Full Version : JS Global



bluewalrus
09-08-2011, 12:17 AM
I'm using the JS variables wrong again but I'm not sure how to correct it.


<script type="text/javascript">
var i = 10;
function num(number) {
if (number < 0)
number--;
else
number = 10;
$("#tempcontainer").append(number);
return number;
}
window.setInterval("num(i)", 1000);
</script>
<div id="tempcontainer"></div>

Basically I just want it to count every 10 seconds and write the seconds to a div.

jscheuer1
09-08-2011, 01:33 AM
There are other problems, but number will never be less than 0.

bluewalrus
09-08-2011, 05:49 AM
Okay, fiddled around some more and got it working.


<script type="text/javascript">
function num(number) {
if (number > 1)
number--;
else
number = 10;
$("#tempcontainer").append(number);
i = number;
}
var i = 10;
window.setInterval("num(i)", 1000);
</script>
<div id="tempcontainer"></div>


There also is a jquery call. I figure this could do this more efficiently in jquery or without jquery, all DOM.

jscheuer1
09-08-2011, 08:44 AM
I'd do something like:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var tc = $('#tempcontainer').append('10'), num = 10, prefix = ', ';
setInterval(function(){
tc.append(prefix + (--num));
if(num < 1){
num = 11;
}
}, 1000);
});
</script>
</head>
<body>
<div id="tempcontainer"></div>
</body>
</html>

If you wanted to do without jQuery:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div id="tempcontainer"></div>
<script type="text/javascript">
(function(){
var tc = document.getElementById('tempcontainer'),
tn = document.createTextNode('10'), num = 10, prefix = ', ', tnc;
tc.appendChild(tn);
setInterval(function(){
tc.appendChild(tnc = tn.cloneNode(false));
tnc.nodeValue = prefix + (--num);
if(num < 1){
num = 11;
}
}, 1000);
})();
</script>
</body>
</html>