javascript loop image slideshow - javascript

var imag = document.getElementById('contentimage');
var imagarr = ["images/contimgtwo.jpg","images/contimg.jpg"]
//var convertimg = imagarr[i].toString();
var runtext = function(){
for (i=0;i<imagarr.length;i++){
imag.src=imagarr[i];
}
}
setTimeout(runtext,5000);
CSS:
#contentimage {
display:block;
top:1600px;
width:500px;
height:400px;
position:absolute;
}
#contentimage:hover {
opacity:0.5;
cursor:crosshair;
}
I'm trying to make a image slideshow using a for loop, the idea is that it will provide the .src path with the image path from the array, however the problem is the .src=" " method requires you to " " so I can't call the array and so it doesn't find the image, any way around this?

You should not loop the whole array in your runtext function. Doing that you actually apply only the last value of the array and always the last image is shown. Here is a modification of your script which may work:
var imag = document.getElementById('contentimage');
var imagarr = ["images/contimgtwo.jpg", "images/contimg.jpg"];
var index = 0, interval;
var runtext = function(){
imag.src = imagarr[index];
if(index < imagarr.length-1) {
index += 1;
} else {
index = 0;
}
interval = setTimeout(runtext, 5000);
}
var stopText = function() {
clearTimeout(interval);
}
interval = setTimeout(runtext, 5000);
I added a function which stops the slideshow. You still go through all the elements of the array, but the index is incremented on every runtext call.

Related

Change an image to a new image with Javascript each time the image is clicked

I have a folder of images and I want to replace the one currently being displayed with another image each time that it is clicked on.
I've managed to make this happen once - i.e. to make the if statement work, but I can't get to the elif statement. Why is the elif condition not being met. Everytime I click it just repeats the if statement, even though the console log shows that the backgroundImage is now budgies: url("http://localhost:3000/images_diamonds/budgies.jpg")
// For clicking on the image
document.querySelector('.diamond-pic').addEventListener('click', () => {
let elem = document.getElementById('pic1');
let ht = window.getComputedStyle(elem, null).getPropertyValue("background");
console.log(ht)
if (document.getElementById('pic1').style.backgroundImage="url(../../images_diamonds/ghecko.jpg)") {
document.getElementById("pic1").style.backgroundImage = "url('../../images_diamonds/budgies.jpg'";
console.log('if achieved')
} else if (document.getElementById('pic1').style.backgroundImage="url(../../images_diamonds/budgies.jpg)") {
document.getElementById("pic1").style.backgroundImage = "url('../../images_diamonds/Christmas_Beetle.jpg'";
console.log('else if achived')
} else {
console.log('else achieved')
}
});
The simplest way to do this is to keep the image names in an array and then just advance the image to the next one in the array when it's clicked.
let counter = 0;
let imgs = [
"https://static4.depositphotos.com/1026550/376/i/600/depositphotos_3763236-stock-photo-gold-star.jpg",
"https://previews.123rf.com/images/lineartestpilot/lineartestpilot1803/lineartestpilot180302423/96543894-cartoon-shooting-star.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTk5tGujYXbv4f9A0pvSuOWC6IhljTzmy4WBw&usqp=CAU",
"http://www.webweaver.nu/clipart/img/nature/planets/smiling-gold-star.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Red_star.svg/2000px-Red_star.svg.png"
];
document.querySelector("img").addEventListener("click", function(event){
this.src = imgs[counter];
// As long as the counter is less than the last index in the array
// increase the counter. Otherwise, start over.
counter = counter < imgs.length-1 ? counter+1 : 0;
});
img { width: 200px;}
<img src="https://previews.123rf.com/images/lineartestpilot/lineartestpilot1802/lineartestpilot180274309/95545188-shooting-star-decorative-cartoon.jpg">
And here's an example when the images are used as backgrounds:
let counter = 0;
let imgs = [
"https://static4.depositphotos.com/1026550/376/i/600/depositphotos_3763236-stock-photo-gold-star.jpg",
"https://previews.123rf.com/images/lineartestpilot/lineartestpilot1803/lineartestpilot180302423/96543894-cartoon-shooting-star.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTk5tGujYXbv4f9A0pvSuOWC6IhljTzmy4WBw&usqp=CAU",
"http://www.webweaver.nu/clipart/img/nature/planets/smiling-gold-star.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Red_star.svg/2000px-Red_star.svg.png"
];
document.querySelector("div").addEventListener("click", function(event){
this.style.background = "url(" + imgs[counter] + ")";
// As long as the counter is less than the last index in the array
// increase the counter. Otherwise, start over.
counter = counter < imgs.length-1 ? counter+1 : 0;
});
div { width: 300px;
height:300px; border:1px solid black; background:url("https://previews.123rf.com/images/lineartestpilot/lineartestpilot1802/lineartestpilot180274309/95545188-shooting-star-decorative-cartoon.jpg");
}
<div></div>

How to cycle through a array with images

I want to know how to click a button and have the array automatically cycle through images at a certain speed per interval, and have the array cycle never end.
Please help me with this
I Have my original code where everytime the user clicks a button the image changes how do I get it so that it only requires one button click and the images constantly cycle.
Thanks in advance
Here is my code:
<img id="colour" src="C:/images/i1">
<button type="button" onclick="light_change()">Cycle Through</button>
<script>
var assets = [
"C:/images/i2",
"C:/images/i3",
"C:/images/i1"
]
i = 0
function light_cycle(){
i = i+1
if(i==assets.length)i=0
var x = document.getElementById('colour');
x.src=assets[i]
}
</script>
this will solve your problem
function light_cycle(){
window.setInterval(function() {
i = i+1
if(i==assets.length)i=0
var x = document.getElementById('colour');
x.src=assets[i]
}, 2000);
}
in the comment place use images[imageNumber] as you wish.
var images = ['imageA.jpg','imageB.jpg','imageC.jpg'];
var getButton = document.getElementById('but');
var getImgContainer = document.getElementById('imgContainer');
var slideTime = 2000;
getButton.onePush = false;
getButton.addEventListener('click',function(event){
if(this.onePush) return;
this.onePush = true;
var imageNumber = 0;
var newInterval = setInterval(function(){
//do something with your urls HERE
console.log(images[imageNumber]);
getImgContainer.setAttribute('src',images[imageNumber]);
if(imageNumber===images.length-1) {
imageNumber = 0;
} else {
imageNumber++;
}
},slideTime);
});
img {
width:200px;
height:200px;
border:solid 1px #33aaff;
}
<button id="but">click me</button>
<br/><br/>
<img src="" id="imgContainer"/>
if i understand right what you want to get, so you need to move the i = i+1 to the end of the function like this :
function light_cycle(){
window.setInterval(function() {
if(i==assets.length)i=0
var x = document.getElementById('colour');
x.src=assets[i]
i = i+1
}, 3000);
}

Javascript array is not recognizing called variable

function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
var i = 0;
while (i <= image.length) {
if (i > image.length) {
i = 0;
}
i += 1;
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
setTimeout('slideShow', 5000);
}
}
I'm unsure why my i variable is not being recognized as the i variable from the rest of the function, so when ever I try to run my while loop it get's an error message saying that it's undefined.
I think you want setInterval instead of setTimeout, and you want you be careful that you increment i after you you update innerHTML.
function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
var i = 0;
setInterval(function () {
if (i === image.length) {
i = 0;
}
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
i++;
}, 5000)
}
slideShow();
You don't need a while loop. You don't need to reset i. You don't need to set innerHTML.
Click Run code snippet... to see how this works. More explanation below the code
function slideShow(elem, images, delay, i) {
elem.src = images[i % images.length];
setTimeout(function() {
slideShow(elem, images, delay, i+1);
}, delay);
}
// setup slideshow 1
slideShow(
document.querySelector('#slideshow1 img'), // target element
[ // array of images
'http://lorempixel.com/100/100/animals/1/',
'http://lorempixel.com/100/100/animals/2/',
'http://lorempixel.com/100/100/animals/3/',
'http://lorempixel.com/100/100/animals/4/',
'http://lorempixel.com/100/100/animals/5/',
'http://lorempixel.com/100/100/animals/6/'
],
1000, // 1000 ms delay (1 second)
1 // start on slide index 1
);
// setup slideshow 2
slideShow(
document.querySelector('#slideshow2 img'), // target element
[ // array of images
'http://lorempixel.com/100/100/nature/1/',
'http://lorempixel.com/100/100/nature/2/',
'http://lorempixel.com/100/100/nature/3/',
'http://lorempixel.com/100/100/nature/4/',
'http://lorempixel.com/100/100/nature/5/',
'http://lorempixel.com/100/100/nature/6/'
],
500, // 500 ms delay
1 // start on slide 1
);
#slideshow1, #slideshow2 {
width: 150px;
display: inline-block;
}
<div id="slideshow1">
<h2>Animals</h2>
<p>(1000 ms delay)</p>
<!-- initial image -->
<img src="http://lorempixel.com/100/100/animals/1/">
</div>
<div id="slideshow2">
<h2>Nature</h2>
<p>(500 ms delay)</p>
<!-- initial image -->
<img src="http://lorempixel.com/100/100/sports/1/">
</div>
This is a huge improvement because your slideshow function is reusable. It means you can use the same function for any slideshow you want. You can even run multiple slideshows on the same page, as I have demonstrated here.
As others have pointed out, the while loop is unnecessary and, as I pointed out, the setTimout was incorrectly written. The following simplifies your code significantly:
var i = 0;
function slideShow() {
var pageSplash = document.getElementById('splash');
var imageArray = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
if(i < imageArray.length) {
pageSplash.innerHTML = '<img title='+ imageArray[i] + ' id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + imageArray[i] + '">';
}
i++;
}
setInterval(slideShow, 2000);
See: https://jsfiddle.net/dauvc4j6/8/ for a working version.
setTimeout calls the function again so you're re-initializing i to 0 every time you call it. Since you can use setTimeout to call the function recursively you don't need the while loop. Pull i out of the function altogether and make it a global variable.
//i should be global
var i = 0;
function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
if (i >= image.length) {
i = 0;
}
i += 1;
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
//set timeout is going to call slideShow again so if it's in the function it will call recursively, if you wanted to stop after a certain point you could nest setTimeout in an if
setTimeout(slideShow, 5000);
}
//you need to initially call the function
slideShow();

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

replacing images inplace

I have a array of static images that I am using for an animation.
I have one frame image that I want to update the image of and I have seen a lot of tutorials on animating images with javascript just simply update the source of an image.
frame.src = animation[2].src; etc
When I look at the resource tracking in chrome, it doesnt look like they are getting cached even thought the web browser does download the image more than once but not once for each time it is displayed, so there is still some browser caching going on.
What is the best way to replace the frame image object with another image?
Well, you can either position all images absolute and give them a z-index, then use jQuery/JS to shuffle their z-indexes, bringing a new one to the top in a cross fader style,
or you can take all the id's and fadeone in slightly faster than the last one fades out.
Like so:
function fader(func) {
var currID = $('#mainimg ul').data('currLI');
var currLiStr = '#mainimg ul li#' + currID;
img = $(currLiStr).find('img').attr('src');
nextID = (currID == 'six') ? 'one' : $(currLiStr).next().attr('id');
nextLiStr = $('#mainimg ul li#' + nextID);
$(currLiStr).fadeOut(3000);
$(nextLiStr).fadeIn(2000).find('div.inner').delay(3000).fadeIn('slow').delay(6000).fadeOut('slow');
$('#mainimg ul').data('currLI',nextID);
}
Note 'six' is the id of the last li, reseting it back to one, but if you do $('#mainimg ul li:last').attr('id'); and $('#mainimg ul li:first').attr('id') to get the last and first id's, you can allow it to cope with any amount of images (obviously this is with li's given id's one, two and so on, but if you are finding out the last and first id you could use any structure.
Or you can set a ul width a width of all the li's multiplied, and give the li's the width of the images, and set overflow to hidden, then use JS to pull the li's left by the width of 1 li on each iteration in a slider like I have done here: http://www.reclaimedfloorboards.com/
There are loads of options
I ended up using jquery's replaceWith command and gave all the frames a class "frame" that i could select with $('.frame') which happened to only select visible frames.
<script type="text/javascript">
var animation = [];
var firstFrame = 1;
var lastFrame = 96;
var animationFrames = 16;
var loadedImageCount = 0;
$(function() {
$("button, input:submit",'#forecastForm').button();
$("#progressbar").progressbar({
value: 0
});
$('#id_Species').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_Layer').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_StartTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_EndTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
});
if (document.images) { // Preloaded images
loadAnimation('Dry_GEM',1,1,96);
}
function rotate(animation, frame)
{
if (frame >= animation.length)
frame = 0;
$('.frame').replaceWith(animation[frame]);
window.setTimeout('rotate(animation,'+eval(frame+1)+')',150);
}
function loadAnimation(species, layer, startTime, endTime)
{
layer = Number(layer);
startTime = Number(startTime);
endTime = Number(endTime);
if (startTime > endTime)
{
swap = startTime;
startTime = endTime;
endTime = swap;
delete swap;
}
for (i=0;i<animation.length;i++)
delete animation[i];
delete animation;
animation = []
$('#progressbar').progressbar({value: 0});
loadedImgCount = 0;
animationFrames = endTime - startTime + 1;
for(i=0;i < animationFrames;i++)
{
animation[i] = new Image();
animation[i].height = 585;
animation[i].width = 780;
$(animation[i]).attr('class','frame');
animation[i].onload = function()
{
loadedImgCount += 1;
$('#progressbar').progressbar({value: eval(loadedImgCount / animationFrames * 100)});
};
animation[i].src = 'http://[[url]]/hemi_2d/' + species + '_' + layer + '_' + eval(i+startTime) + '.png';
}
}
</script>
The easiest way to do it is create a separate hidden image for each frame. Something like this:
var nextImage = (function(){
var imagePaths='basn0g01.png,basn0g02.png,basn0g04.png,basn0g08.png'.split(','),
imageHolder=document.getElementById('custom-header'),
i=imagePaths.length, imageIndex=i-1, img;
for (;i--;) {
img=document.createElement('img');
img.src='http://www.schaik.com/pngsuite/' + imagePaths[i];
if (i) img.style.display='none';
imageHolder.appendChild(img);
}
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());
Try this example on this page; paste it in the console and then call nextImage() a few times. Watch the top of the page.
edit
If you already have all the images in your HTML document, you can skip most of the above and just do something like this:
var nextImage = (function(){
var imageHolder=document.getElementById('custom-header'),
images=imageHolder.getElementsByTagName('img'),
i=images.length, imageIndex=0, img;
for (;i--;) if (i) images[0].style.display='none';
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());

Categories

Resources