Use of setTimeout - how to pass parameters? - javascript

I am trying to develop a slideshow with a pause between slides. So I'm trying to use the setTimeout statement as shown below. This is written to swap 2.jpg for 1.jpg with a pause of 10 seconds on clicking the button. But it does now work. Can anyone help me. Thanks.
<html>
<head>
<script type="text/javascript">
var t;
function swap(newImage) {
var fileName=newImage.toString()+".jpg"
document.slideshow.src=fileName
t=setTimeout("swap()",10000)
}
</script>
</head>
<body>
<img name="slideshow" src="1.jpg" width="450" height="335" />
<br /><br />
<input type="button" onClick="swap('2')" value="Change image" />
<br /><br />
</body>
</html>

There are a couple of things wrong here. First, its passing code to be eval'ed in the first parameter of setTimeout is not recommended. Better pass a callback instead:
setTimeout(function() { swap(); },10000);
//Or
setTimeout(swap,10000); //Passing the actual function as the callback
Second, you are calling the swap() method without parameters inside the timeout. It should pass in a new image filename (perhaps by declaring an array of filenames), or check whether the parameter is set or not.
function swap(newImage,element) {
if(newImage) {
var fileName = newImage.toString()+".jpg";
element.src = fileName;
}
t=setTimeout(this,10000)
}
This function obviously won't do anything after the first run (since no new image filenames are supplied). Using an array you could iterate over several filenames:
var images = ['1.jpg','2.jpg','3.jpg'];
var slideshow = function(element, images, index) {
if(!index || ( (index + 1) > images.length) ) index = 0;
element.src = images[index];
t = setTimeout(function(){
slideshow(element, images, index + 1);
},10000)
};
//Fetch the image element the slideshow is running on
var element = document.slideshow;
slideshow(element, images);
This will continue switching between the images in the array until the timeout is canceled.

Your swap function requires a parameter, so it won't work with setTimeout.

Javascript isn't necessary to do a slideshow. All you have to do is put each image into a separate page, then add this single line to the top of each page in the <head> section:
<meta http-equiv="refresh" content="10;url=NextPage.html"/>
"10" is the number of seconds to wait before going to the next page, and "NextPage.html" is the link to the page containing the next image to display.

Related

Javascript if statements in displaying images

Hey i am currently trying to get a program running in javascript i want the program to display the 4 images one after each other with the single press of a button and then after the 4 images have cycled through i want them to stop cycling and i cant seem to do it this is my code i currently have:
<html>
<head>
<script>
var images = ["image1.png","image2.png","image3.png","image4.png"];
var imagenum = 0;
var timer;
function imageCycle()
{
if(++imagenum == 4)
imagenum = 0;
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
</script>
</head>
<body>
<img src="image1.png" name="image" width=800 height=600>
<form>
<input type="button" value="images" name="cycle images" onclick="imageCycle()">
</form>
</body>
</html>
any help is appreciated many thanks!
In your code you continue to schedule the function, that's why the images continue to rotate.
If you want to stop at the forth image displayed, you have to put the setTimeout line in an else statement.
if (++imagenum == 4) {
imagenum = 0;
} else {
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
Another point, that other users notice and I just report here in my answer.
You use the string:
imageCycle()
as the first argument of setTimeout, insted you should use just the function name.
timer = setTimeout(imageCycle, 1000);

JavaScript replace img src with External src

I'm having a strange problem that I can't quite figure out.
I have a normal image on a web page
<img src="images/logo.png"/> <!-- getting image from root directory -->
and I have some javascript code to replace the image source
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; image++)
image[num].src = image[num].src.replace("images/pic01.png", "images/other/pic02.png")
}
This code works fine which is great although it seems to fall down as soon as the src I want it replaced to is outside of my root directory such as "http://www.servername.com/pic03.png" // (this is an imaginary URL don't try to click it).
is there a reason this happens? is there a way around this?
The problem is that you are only replacing the last part of your original src. The src of the img tag first looks like this:
"http://yourserver.com/images/pic01.png"
...and after replacing "images/pic01.png" with you external URL, it looks like this:
"http://yourserver.com/http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png"
To avoid this problem you can try this:
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; num++) {
if (stringEndsWith(image[num].src, "images/pic01.png")) {
image[num].src = "http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png";
}
}
}
function stringEndsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1
}
There's also an error in your for loop, where you are incrementing image instead of num
Step-by-step explanation
imageUpdate()
Loop through each img tag and look at the src attribute
If src ends with "images/pic01.png" replace all of src with the new url
stringEndsWith()
Find index of given suffix (start looking for the suffix at the last possible position
the suffix can be located at)
If this index is found (is different from -1) return true, else return false
What target url are you assigning to it? Make sure that it is pointing to an absolute address (keep the http:// part at the beginning).
If the file is in the same server, you can still use relative file paths, and go up a parent folder by using two dots. For instance: ../someotherfolder/pic03.jpg
<script>
function imageUpdate() {
document.getElementById('imageT').src = 'test.jpg';
}
</script>
<img id='imageT' src="images/logo.png"/> <!-- getting image from root directory -->
JS Fiddle-Demo
There is an error in the link you are trying to use. The actual link should be:
http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png
Here is come code to demonstrate:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
function changeImage() {
document.getElementById('changeThis').src = 'http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png'
}
</script>
</head>
<body>
<img id="changeThis" src="http://www.wartburgseminary.edu/uploadedImages/Resources/small-twitter-icon.jpg">
<input type="button" value="Change" onClick="changeImage()">
</body>
</html>

Image changing loop not working

I have written a JavaScript that is supposed to change my header image every three seconds. For some reason nothing happens when I'm opening my page.
Can anyone see what I'm doing wrong?
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="changeImage.js"></script>
<title>Mikael Mattsson</title>
</head>
<body>
<div class="header">
<img id="headerImg" src="images/header-image.png" alt="Header image" width="100%" hight="100%">
</div>
</body>
</html>
JavaScript:
var images = [];
images[0] = "images/header-image.png";
images[1] = "images/header-image2.png";
var x = 0;
function imageChanger(){
var img = document.getElementById("headerImg");
img.src = images[x];
x++;
if (x > images.length){
x = 0;
}
setTimeout("imageChanger()", 3000);
}
x > images.length should be x >= images.length.
setTimeout("imageChanger()", 3000); must be changed to setTimeout(imageChanger, 3000);
You call the setTimeout inside the function but never call the function. So the timeout is never set, hence the function is not called through the timeout.
I recommend using setInterval above setTimeout in your case since you want to have the function executed repeatedly. Also you could improve the way you increase x.
var x = 0;
function imageChanger() {
var img = document.getElementById("headerImg");
x = (x + 1) % images.length; // Make sure x is never larger than images.length
img.src = images[x];
}
// Start calling the function after a delay of 3000ms
setInterval(imageChanger, 3000);​​​​
I also recommend using a better name than x for your counter variable, but that is up to you!
You're close. You need to change two things.
First, you need to call the imageChanger function at least once to kick off the code. At the end of your script, add:
imageChanger();
Your code may work from there. However, instead of passing a string to setTimeout(), you should instead pass a reference to the function itself:
setTimeout(imageChanger, 3000);
You should be all set. Let me know if you have issues.
Remove
setTimeout("imageChanger()", 3000);
And add
window.onload=function() {
setInterval(imageChanger, 3000);
}
Outside the function
And as pointed out, change > to >=

I can't get my image slideshow to work using JavaScript

I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.
picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.
You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>

Replace image with another image, then replace again after timeout - Javascript

I'm trying to do the following:
onClick, replace image1 with image2, then after 5 seconds, replace image 2 with image 1 again.
Image 1 is replaced with image 2, but my problem is that it doesn't revert back after the timeout.
Here is my code:
<img id="loadimg" style="display:none;" src="images/Loader.gif" width="140" height="30" />
<script type="text/javascript" language="javascript">
function showLoad(){
document.getElementById('Generate1').src=document.getElementById('loadimg').src;
setTimeout(showCode(), 5000);
}
function showCode(){
document.getElementById('loadimg').src=document.getElementById('Generate1').src;
}
</script>
<td colspan="3" rowspan="3"><img src="images/BUTTON.gif" alt="" name="Generate1" width="168" height="40" id="Generate1" onClick="showLoad()"></td>
Thanks for any help.
That is because old images is being "run-over" by new one. You could do something like this:
var pathToGenerateImg = "..."; // path to generate
var pathToLoadImg = "..."; // path to load img
function showLoad(){
document.getElementById('Generate1').src = pathToLoadImg;
setTimeout(showCode, 5000);
}
function showCode(){
document.getElementById('Generate1').src = pathToGenerateImg ;
}
In this case you only need single <IMG> container (with id="Generate1") as all paths are stored in variables.
You have to address the same image with id Generate1 and store initial image src in temp value (e.g. var image):
var image = document.getElementById('Generate1').src;
function showLoad(){
document.getElementById('Generate1').src = document.getElementById('loadimg').src;
setTimeout(showCode, 5000);
}
function showCode(){
document.getElementById('Generate1').src = image;
}
You don't want to run showCode and pass the result to setTimeout, you want to pass the function itself as an argument to setTimeout so it can be called back:
setTimeout(showCode, 5000);
Also, when you assign document.getElementById('loadimg').src to document.getElementById('Generate1').src, doing the reverse won't change anything. You need to keep the original in a variable. You may as well keep your elements in variables, too:
var Generate1 = document.getElementById('Generate1');
var loadimg = document.getElementById('loadimg');
var originalSrc = Generate1.src;
function showLoad() {
Generate1.src = loadimg.src;
setTimeout(showCode, 5000);
}
function showCode() {
loadimg.src = originalSrc;
}

Categories

Resources