How do I cycle through pictures in JavaScript? - javascript

My html:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
My Javascript:
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
Everything makes sense to me but for some reason it is not working. It is only showing the first picture (doesn't cycle through the pictures). Please let me know if you need anything else. Thank you.

you are getting element 'rotator' before document is loaded so it doesn't exist.
Try this:
function start() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 1;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
window.onload=function(){
start();
}

Preload the images:
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstcar.gif" // set image src property to image path, preloading image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcar.gif"
slideimages[2] = new Image()
slideimages[2].src = "thirdcar.gif"
</script>
Display the first image:
<img src="firstcar.gif" id="slide" width="100" height="56" />
Create the slideshow(cycle):
<script type="text/javascript">
//variable that will increment through the images
var step=0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
if (step<2)
step++
else
step=0
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
</script>

This is how you can try...it works fine for me....
<html>
<body>
<img src="file:///C:/Users/Public/Pictures/Sample%20Pictures/test1 (2).jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'file:///C:/Users/Public/Pictures/Sample%20Pictures/';
var delayInSeconds = 5;
var images = ['test1.jpg', 'test1 (2).jpg', 'test1 (3).jpg', 'test1 (4).jpg', 'test1 (5).jpg', 'test1 (6).jpg', 'test1 (7).jpg', 'test1 (8).jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 100);
})();
</script>
</body>
</html>

You try to access the DOM element with the id rotator before it got loaded.
There are two ways to bypass this problem:
You can move your script tag below the img tag, because then the javascript get's execute after the img element has been loaded:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
You can set the onload event handler for the document to your anonymous function (or give it a name if you like):
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
</script>

Related

Slow down image cycle rotation to eventual random stop

I have a list of images that the code cycles through and displays indefinitely.
I want it to slow down and stop on a random image in the list.
Can anyone help me with this?
This is what I have so far:
<div id="imgSelect" class="imgSelect">
<div id="img" class="img">
<img id="imgDisplay" class="imgInside" imgalt="rArrowback">
</div>
<div id="select" class="select">
<button id="selectBtn" type="button" class="btnSelect">GO!</button>
</div>
</div>
The funtion:
var imgArray = new Array();
for (var i = 0; i < 60; i++) {
imgArray[i] = './imgs/' + i + '.png';
}
document.getElementById("imgDisplay").style.backgroundImage = "url('qm.png')"
function selectImg() {
document.getElementById("imgDisplay").style.backgroundImage = 'none'
var rotator = document.getElementById("imgDisplay");
var delayInSeconds = 1;
var num = 0;
var changeImage = function () {
var len = imgArray.length;
rotator.src = imgArray[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 100);
// for (var i = 0; i < 60; i++) {
// document.getElementById("imgDisplay").style.backgroundImage = "url('" + imgArray[i] + "')"
// }
}
This is the result:
Use the random function offered by Javascript.
Right after the timer put rotator.src = imgArray[Math.floor(Math.random() * imgArray.length)];

javascript: image change for certain times

I found this script :
<html>
<head>
<script type="text/javascript">
var paths = ['assets/img/head.png','assets/img/tail.png'];
var curPic = 1;
var imgO = new Array();
for(i=0; i < paths.length; i++) {
imgO[i] = new Image();
imgO[i].src = paths[i];
}
function swapImage() {
curPic = (++curPic > paths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,200);
}
window.onload=function() {
imgCont = document.getElementById('img');
swapImage();
}
</script>
</head>
<body>
<div>
<img id="img"/>
</div>
</body>
</html>
this repeate changing the pictures for unlimited time, but how do I change this that it repeats for e.g. 5 times only ?
Just use a tracker variable.
var to, times = 0; //<-- init the tracker, and a var for the timeout
function swapImage() {
if (times == 5) {
clearTimeout(to); //<-- if already 5 times, cancel timeout and...
return; //<-- ...quit
}
curPic = (++curPic > paths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
to = setTimeout(swapImage,200); //<-- make the TO accessible via our var
times++;
}

Add captions to very basic jquery carousel

I've seen this very simple jquery styled carousel on another thread and think it would be ideal for a project I'm doing but wondering how it could be adapted to include captions on the images?
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.png";
path[1] = "image_2.png";
path[2] = "image_3.png";
function swapImage() { document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",2000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
Any help or suggestions without having to overhaul the carousel would be greatly appreciated!
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = {img: "image_1.png", sub: "subtitle 1"};
path[1] = {img: "image_2.png", sub: "subtitle 2"};
path[2] = {img: "image_3.png", sub: "subtitle 3"};
function swapImage() {
document.slide.src = path[i].img;
document.subtitle.innerHTML = path[i].sub;
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",2000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
<p name="subtitle"></p>
It's very simple, sample below, also notice, that demo uses setInterval instead of setTimeout
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "http://lorempixel.com/400/200/sports/1";
path[1] = "http://lorempixel.com/400/200/sports/2";
path[2] = "http://lorempixel.com/400/200/sports/3";
function swapImage() {
document.slide.src = path[i];
// for the sake of example, we show urls of pictures
document.querySelector('#slide_caption').textContent = path[i];
if (i < path.length - 1) {
i++;
} else {
i = 0;
}
}
setInterval(swapImage, 2000);
window.onload = swapImage;
<h3 id="slide_caption"></h3>
<img height="200" name="slide" width="400" />

JavaScript Mouse Over Pause

I am really getting frustrated with my JS slideshow, I am trying to implement a mouse-over pause function in the slideshow. All I need the slideshow to do is pause when the user hovers over the slide. Seems easy right?! No, I have tried incorporating different functions but nothing seems to stick with the code.
<script type="text/javascript">// <![CDATA[
var imgs1 = new Array("http://www.cmsplc.com/media/wysiwyg/CMS_XMAS_BANNER_2.jpg","http://www.cmsplc.com/media/wysiwyg/Dymo_XTL_Range.jpg","http://www.cmsplc.com/media/wysiwyg/Banners/Homepage_Banners/Promotional_Banners/Fluke_Cashback_Upgrade_1.jpg","http://www.cmsplc.com/media/wysiwyg/Fluke_DTX_Buy_Back_2015.jpg");
var lnks1 = new Array("http://www.cmsplc.com/christmas-opening-times","http://www.cmsplc.com/dymo-xtl","http://www.cmsplc.com/fluke-dsx-upgrade-sept-2015/","http://www.cmsplc.com/fluke-networks-dtx-upgrade-offer/");
var alt1 = new Array();
var currentAd1 = 0;
var imgCt1 = 4;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",4000);
// ]]></script>
<p><a id="adLink1" target="_top"><img id="adBanner1" src="http://www.cmsplc.com/media/wysiwyg/CMS_XMAS_BANNER_2.jpg" border="0" alt="" width="804" height="300" /></a></p>
Where abouts in the above will I need to include the pause functions??!
A few changes. Give it this way:
// Put this on top.
var intvl = 0;
// Replace the setInterval line.
intvl = window.setInterval("cycle1()",4000);
And add this event handler:
// Add this at the end, may be before `<body />` inside a `<script>` tag.
adBanner1.onmouseover = function () {
clearInterval(intvl);
}
adBanner1.onmouseout = function () {
intvl = window.setInterval("cycle1()",4000);
}
Full Code
<p><a id="adLink1" target="_top"><img id="adBanner1" src="http://www.cmsplc.com/media/wysiwyg/CMS_XMAS_BANNER_2.jpg" border="0" alt="" width="804" height="300" /></a></p>
<script type="text/javascript">// <![CDATA[
var imgs1 = new Array("http://www.cmsplc.com/media/wysiwyg/CMS_XMAS_BANNER_2.jpg","http://www.cmsplc.com/media/wysiwyg/Dymo_XTL_Range.jpg","http://www.cmsplc.com/media/wysiwyg/Banners/Homepage_Banners/Promotional_Banners/Fluke_Cashback_Upgrade_1.jpg","http://www.cmsplc.com/media/wysiwyg/Fluke_DTX_Buy_Back_2015.jpg");
var lnks1 = new Array("http://www.cmsplc.com/christmas-opening-times","http://www.cmsplc.com/dymo-xtl","http://www.cmsplc.com/fluke-dsx-upgrade-sept-2015/","http://www.cmsplc.com/fluke-networks-dtx-upgrade-offer/");
var alt1 = new Array();
var currentAd1 = 0;
var imgCt1 = 4;
var intvl = 0;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
intvl = window.setInterval("cycle1()",4000);
adBanner1.onmouseover = function () {
clearInterval(intvl);
}
adBanner1.onmouseout = function () {
intvl = window.setInterval("cycle1()",4000);
}
// ]]>
</script>

How to Change the Source of an Image W/JS

I have to change the src of an image using java script and I am pretty sure i hit a road block, in the html I have 3 li elements and in the id is the source of the mouseenter img. I feel like I am close but so far. Heres my code so far. Thanks for any help!
Javascript:
var $ = function (id) {
return document.getElementById(id);};
window.onload = function () {
var links = document.getElementsByTagName("li"),
imgElements = document.getElementsByTagName("img"),
imgNode,
i,
URLone,
URLtwo,
link,
image;
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
}
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
HTML ::
<body>
<section>
<h1>Ram Tap Combined Test</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
Working jQuery :
$(document).ready(function() {
$("#image_rollovers img").each(function() {
var oldURL = $(this).attr("src"); // gets the src attribute
var newURL = $(this).attr("id"); // gets the id attribute
// preload images
var rolloverImage = new Image();
rolloverImage.src = newURL;
$(this).hover(
function() {
$(this).attr("src", newURL); // sets the src attribute
},
function() {
$(this).attr("src", oldURL); // sets the src attribute
}
); // end hover
}); // end each
}); // end ready
for (i = 0; i < imgElements.length; i++) {
(function(imgNode) {
imgNode.addEventListener("mouseenter", function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}, false);
imgNode.addEventListener("mouseout", function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
}, false);
})(imgElements[i]);
}
A couple of problems in your code.
First for loop closing right away, instead should close after your
imgNode.mouseout function
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
}
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
Last for loop runs 6 times but there are only 3 tags in html. When it coming to loop no. 3 it doesn't get any value for link.src.
Also links variable provides a collection of 'li' tags and not 'img', last for loop requires src from link.src which doesn't have any value, need to change
var links = document.getElementsByTagName("li"),
to
var links = document.getElementsByTagName("img"),
Try that. Hopefully after correcting above errors your code should work.

Categories

Resources