Traffic Light Code - javascript

Below is my code... it works perfectly fine but...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<img id="trafficlights" src="Redlight.jpeg" style="width:128px;height:128px;">
<button type="button" onclick="changetrafficlights()">Change Traffic Lights</button>
<script>
var position = 0;
var list = ["Redlight.jpeg","RedAmberlight.jpeg","Greenlight.jpeg", "Amberlight.jpeg"];
function changetrafficlights()
{position = position + 1;
if(position == list.length){
position = 0;
}
var image = document.getElementById('trafficlights');
image.src=list[position];}
</script>
</body>
</html>
I'm trying to make a javascript code in which will use a while loop or for loop in which will go through the variable "list" automatically

You can use setInterval() for that in the following way:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<img id="trafficlights" src="Redlight.jpeg" style="width:128px;height:128px;">
<button type="button" onclick="starttrafficlights()">Change Traffic Lights</button>
<button type="button" onclick="stoptrafficlights()">Stop Traffic Lights</button>
<script>
var position = 1, id;
var list = ["Redlight.jpeg","RedAmberlight.jpeg","Greenlight.jpeg", "Amberlight"];
function changetrafficlights(){
stop = true;
var image = document.getElementById('trafficlights');
image.src=list[position % list.length];
position++;
}
function starttrafficlights(){
id = setInterval(changetrafficlights, 1000);
}
function stoptrafficlights(){
clearInterval(id);
}
</script>
</body>
</html>
This will automatically change the img after the specified duration.
Hope it Helps!!

Related

jquery preloaded imgages with rollovers

So I am doing something very basic that can be done with CSS but I want to do it with jQuery to get familiar with the library.
I am trying to create a rollover image gallery. Where when you put the mouse over the image it will be swapped with a slightly edited version of it.
Here is the 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>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<style>
</style>
</head>
<body>
<div id="gallery">
<img src="images/one_s.jpg" />
<img src="images/two_s.jpg" />
<img src="images/three_s.jpg" />
<img src="images/four_s.jpg" />
<img src="images/five_s.jpg" />
<img src="images/six_s.jpg" />
</div>
<script>
$(document).ready(function(){
var alternate = ['images/one_s_edited.jpg',
'images/two_s_edited.jpg',
'images/three_s_edited.jpg',
'images/four_s_edited.jpg',
'images/five_s_edited.jpg',
'images/six_s_edited.jpg'];
var $selection = $("#gallery img");
for(var i = 0; i < alternate.length; i++)
{
var imgObject = new Image();
var downloadedImg = imgObject.src = alternate[i];
console.log(downloadedImg);
var originalSrc = $selection.eq(i).attr("src");
console.log(originalSrc + "\n");
$selection.eq(i).hover(
function(){
$(this).attr("src", downloadedImg);
},
function(){
$(this).attr("src", originalSrc);
}
);//End hover
}//End loop
});//End ready
</script>
</body>
</html>
Here is a link to the final result: link
As you can see it rolls over but not as planned. It ends up with the last rollover-image and doesn't change back to the original nor does it show the appropriate rollover image that corresponds with it.
Any simple suggestions without using regular expressions?
The problem is the wrong usage of a closure variable in a loop.
But the solution can be simplified to
$(document).ready(function () {
var $selection = $("#gallery img");
$selection.hover(function () {
this.src = this.src.replace('.jpg', '_edited.jpg')
}, function () {
this.src = this.src.replace('_edited.jpg', '.jpg')
})
}); //End ready

JavaScript access iframe inner variables in Firefox

The following works well in Internet Explorer and Chrome, but NOT in Firefox.
The idea is to change the background of the parent body after every click within the iframe.
Note that Firefox somehow knows to set the blue background initially.
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><script>
function polling() {
if (window.iframeId.change) document.body.style.background = 'red';
if (!window.iframeId.change) document.body.style.background = 'blue';
setTimeout(polling, 1000); }
</script></head>
<body onload="polling();">
<iframe id="iframeId" src="frame.html" style="width:100px; height:100px;"></iframe>
</body>
</html>
frame.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><script>var change=false;</script></head>
<body style="background:yellow;" onclick="change=!change;"></body>
</html>
This is how I could make it work:
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script>
function polling() {
if (window.frames['theIframe'].change) {
document.body.style.background = 'red';
}
else {
document.body.style.background = 'blue';
}
setTimeout(polling, 1000);
}
</script>
</head>
<body onload="polling();">
<iframe id="iframeId" src="frame.html" name="theIframe" style="width: 100px; height: 100px;"></iframe>
</body>
</html>
frame.html
<!DOCTYPE HTML >
<html>
<head>
<script>
var change = false;
function load() {
document.onclick = doClick;
}
function doClick() {
change = !change;
}
</script>
</head>
<body style="background: yellow;" onload="load()"></body>
</html>

Displaying a part of DIV in iframe

I am using HTML object in below manner
<object id="foo" name="foo" type="text/html" data="mypage.aspx">
</object>
Now, I don't want to display complete data in mypage.aspx in HTML object/iframe. I just want to display a DIV layer from mypage.aspx in current page (default.aspx). I tried using data="mypage.aspx#div1" but didn't work.
For testing purpose mypage.aspx consists of
<body>
<div id="div1">This has to be displayed</div>
<div id="div2">This should not be displayed</div>
This portion also should not be displayed
</body>
How can I display only DIV1 part of mypage.aspx in HTML object?
If you can get rid of using object or iframe you can use jQuery load method to just get the required mark up from mypage.aspx. Keep a container in your parent page which will hold the required content from mypage.aspx and try this.
$(function(){
//Here container is a div in which #div1 from mypage.aspx will be loaded.
$('#container').load('mypage.aspx #div1');
});
If you want to read about Loading Page Fragments using jQuery take a look at this link
I don't have an aspx capable server. So I tested using plain html, but the principle is the same really.
I recreated test.html:
<body>
<div id="div1">This has to be displayed</div>
<div id="div2">This should not be displayed</div>
This portion also should not be displayed
</body>
Then I made test2.html and for simplicity I embedded the JavaScript in test2.html:
<!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 id="Head1" runat="server">
<title>Test</title>
<script language="javascript"type="text/javascript">
function init() {
var obj = document.getElementById("foo"); // Grab the frame element
var kids = obj.contentDocument.body.childNodes; // Grab all child nodes of the body node of fram element
for( var i = 0; i < kids.length; i++ ) { // iterate through all child nodes
if( kids[i].id == "div1" ) { // if child node's id is "div1"
alert(kids[i].firstChild.nodeValue); // alert the first child of the div, e.g. text node, value
}
}
}
window.onload = init;
</script>
</head>
<body>
<object id="foo" name="foo" type="text/html" data="test.html"> </object>
</body>
</html>
This approach seemed the most cross-browser compatible naked javascript I could create. I'm not claiming that it's the best possible solution, though.
Here's some additional things you can do, I wrote comments for each. I commented one of the lines out because it makes a dramatic change I'm not sure you'd like. You can try it, though.
<!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 id="Head1" runat="server">
<title>Test</title>
<script language="javascript"type="text/javascript">
function init() {
var myDiv = document.createElement("div"); //create a new div
myDiv.innerHTML = "<strong>Testing!</strong>"; // add some HTML to myDiv
var obj = document.getElementById("foo"); // Grab the frame element
var kids = obj.contentDocument.body.childNodes; // Grab all child nodes of the body node of fram element
for( var i = 0; i < kids.length; i++ ) { // iterate through all child nodes
if( kids[i].id == "div1" ) { // if child node's id is "div1"
kids[i].firstChild.nodeValue = "sts"; // change first text node to sts
kids[i].appendChild( myDiv ); //append myDiv to Div1
document.getElementById("container").innerHTML = kids[i].firstChild.nodeValue; // add text to container
//document.getElementById("container").appendChild(kids[i]); // actually append, or insert div1 into container2, this should move the div1 out of the frame and into the document
}
}
}
window.onload = init;
</script>
</head>
<body>
<object id="foo" name="foo" type="text/html" data="test.html"> </object>
<div id="container"></div>
<div id="container2"></div>
</body>
</html>

Problem with going idle and active with jquery: when active update useronline timestamp on mysql

I want to update the timestamp on useronline database only when people aren't idle (keyboard mouse active for some time-I am using a jquery plugin for that) The problem for me is that I can't clear the interval for the function so in my test script below, when it starts counting it never stops and even when active again it starts another counter so that its like its counting twice as fast. How am I supposed to stop that timer? Its like the counter has never been started when its idle- so it can't find it to stop it.
In the real script the counter will be $.get()-ing the php that updates the mysql table. For that reason i'm using intervals, or it would get on every mouse move right? and that would be loading the server.
http://jsbin.com/uleza5 to test just don't move mouse for 6 seconds then see the idle text, then move the mouse and it will start counting; after 6 seconds it will go idle again when inactive.
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="js/jquery_plugin_timer2.js"></script>
<script src="https://github.com/paulirish/jquery-idletimer/raw/master/jquery.idle-timer.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
$(document).ready(function(){
$('.status').html('active');
});
x = 0;
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 6000;
var it;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
var it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="js/jquery_plugin_timer2.js"></script>
<script src="https://github.com/paulirish/jquery-idletimer/raw/master/jquery.idle-timer.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
var it;
$(document).ready(function(){
$('.status').html('active');
});
x = 0;
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 6000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>

Image Hidden, then on mouse movement Fade-In, Fade-Out and Fade-In again

I am trying to get an image to fade out when there has been no mouse action for 3 seconds and then fades in when the mouse is again moved.
I would also be appreciative if anyone could tell me how I can make the image be hidden until the mouse moves. So when the page loads up you don't see the image until the mouse moves.
This is what I have so far...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 TRANSITIONAL//EN">
<html>
<head>
<title></title>
<script type="text/javascript">
var timer;
$(document).mousemove(function() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
$('#top:visible').fadeIn();
timer = setTimeout(function() {
$('#top').fadeOut()
}, 3000)
})
</script>
</head>
<body>
<div id="top">
<img src="graphics/logo/logo.psd" title="" alt="">
</div>
</body>
</html>
Thanks so much for your help!
I've updated my answer with an all-in-one page. Hopefully this will make things more clear. Better to have javascript in its own file, but this will get you going.
Make sure that this line:
<script type="text/javascript" src="jquery-1.4.1.min.js"></script>
correctly points to your jQuery file with the right location and name.
Let me know how it goes.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>tester page</title>
<style>
<!--
-->
</style>
<script type="text/javascript" src="jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $top = $('#top');
var $document = $(document);
var timer = null;
var timerIsRunning = false;
$top.hide();
$('#menu').mousemove(function(e){
e.stopPropagation();
});
setTimeout(function() {
$document.mousemove(function(e) {
if($top.is(':hidden')) {
$top.fadeIn();
} else {
if(!timerIsRunning) {
timerIsRunning = true;
clearTimeout(timer);
timer = setTimeout(function() { $top.fadeOut(); }, 5000);
setTimeout(function() {timerIsRunning = false;}, 2000);
}
}
});
}, 500);
});
</script>
</head>
<body>
<div id="top">
<img src="graphics/logo/logo.psd" title="" alt="">
</div>
</body>
</html>
Try this:
$(document).ready(function() {
var timer;
// hide initially
$('#top').hide();
$(document).mousemove(function() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
$('#top').fadeIn();
timer = setTimeout(function() {
$('#top').fadeOut();
}, 3000)
});
});

Categories

Resources