Create a timer to go through images - javascript
Using Javascript and HTML I need to create a timer to display the pictures every 3 seconds. I need to use the array to do this and keep the onclick available.
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<title> Image Swapping</title>
<div id=getPhoto></div>
<script>
var images = ["image1.jpg", "image2.jpg", "image3.jpg", image4.jpg"];
function changeImage(newImage) {
var image = images[newImage];
newImage = document.getElementById("bigPic");
newImage.src = image;
}
var myTimer = setInterval(chose(), 3000);
var divVariable = document.getElementById("images");
function chose(){
var rand = Math.ceil(Math.random() * images.length);
}
document.getElementById('newImage').src = images[rand];
</script>
</head>
<body>
<div>
<img src="image1.jpg" id="bigPic" style="width:60%" />
</div>
<img src="image1.jpg" id="img1" onclick="changeImage(0)" />
<img src="image2.jpg" id="img2" onclick="changeImage(1)" />
<img src="image3.jpg" id="img3" onclick="changeImage(2)" />
<img src="image4.jpg" id="img4" onclick="changeImage(3)" />
</div>
</body>
</html>
You've got some learning to do... there's a lot of things wrong with your code:
a div in the head?
forgot a " in images array
overwriting param in changeImage is not a good idea
using () in setInterval will call the function immediately, and only once
chose() doesn't do anything
array index is 0-based (0-3 for images array) but you're rounding up your random number (1-4)
Open your browser console and check for errors.
You probably need something like this (not tested):
<script>
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"];
function changeImage( idx ) {
var newImage = document.getElementById("bigPic");
newImage.src = images[idx];
}
function chose(){
var rand = Math.floor(Math.random() * images.length);
changeImage(rand);
}
chose(); // call immediately
var myTimer = setInterval(chose, 3000);
</script>
Related
Problem with randomly pre-loaded image when changing image every 15 seconds
I'm a newbie at coding and this is for a school project. I'm trying to change an image every 15 seconds, and I have figured out how to do it. however, I want an image to be shown immediately and not after 15 seconds. my code is below: <!DOCTYPE html> <html> <body> <div class="center"> <img src="" id="image"> </div> <script type="text/javascript"> let image = document.getElementById('image'); let images = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png', 'image6.png', 'image7.png', 'image8.png', 'image9.png', 'image10.png', 'image11.png', 'image12.png', 'image13.png', 'image14.png', 'image15.png', 'image16.png', 'image17.png', 'image18.png', 'image19.png', 'image20.png', 'image21.png', 'image22.png', 'image23.png', 'image24.png', 'image25.png', 'image26.png', 'image27.png', 'image28.png', 'image29.png', 'image30.png', 'image31.png', 'image32.png', 'image33.png', 'image34.png', 'image35.png', 'image36.png', 'image37.png', 'image38.png', 'image39.png', 'image40.png', 'image41.png', 'image42.png', 'image43.png', 'image44.png', 'image45.png', 'image46.png', 'image47.png', 'image48.png', 'image49.png', 'image50.png', 'image51.png', 'image52.png', 'image53.png', 'image54.png', 'image55.png', 'image56.png', 'image57.png', 'image58.png', 'image59.png', 'image60.png', 'image61.png', 'image62.png', 'image63.png', 'image64.png', 'image65.png', 'image66.png', 'image67.png', 'image68.png', 'image69.png', 'image70.png', 'image71.png', 'image72.png', 'image73.png', 'image74.png', 'image75.png', 'image76.png', 'image77.png', 'image78.png', 'image79.png', 'image80.png', 'image81.png', 'image82.png', 'image83.png', 'image84.png', 'image85.png', 'image86.png', 'image87.png', 'image88.png', 'image89.png', 'image90.png', 'image91.png', 'image92.png', 'image93.png', 'image94.png', 'image95.png', 'image96.png', 'image97.png', 'image98.png', 'image99.png', 'image100.png'] setInterval(function(){ let random = Math.floor(Math.random() * 100); image.src = images[random]; }, 15000); </script> </body> </html> I know I can change the image by manipulating the src attribute of the img tag, but I want a random image to be shown upon load. I've been trying to find a solution but I couldn't find any. Can anyone help me with how to do this?
You just have to add those two instructions after the creation of the images list and before the setInterval. let random = Math.floor(Math.random() * 100); image.src = images[random]; That is the code you will obtain: <!DOCTYPE html> <html> <body> <div class="center"> <img src="" id="image"> </div> <script type="text/javascript"> let image = document.getElementById('image'); let images = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png', 'image6.png', 'image7.png', 'image8.png', 'image9.png', 'image10.png', 'image11.png', 'image12.png', 'image13.png', 'image14.png', 'image15.png', 'image16.png', 'image17.png', 'image18.png', 'image19.png', 'image20.png', 'image21.png', 'image22.png', 'image23.png', 'image24.png', 'image25.png', 'image26.png', 'image27.png', 'image28.png', 'image29.png', 'image30.png', 'image31.png', 'image32.png', 'image33.png', 'image34.png', 'image35.png', 'image36.png', 'image37.png', 'image38.png', 'image39.png', 'image40.png', 'image41.png', 'image42.png', 'image43.png', 'image44.png', 'image45.png', 'image46.png', 'image47.png', 'image48.png', 'image49.png', 'image50.png', 'image51.png', 'image52.png', 'image53.png', 'image54.png', 'image55.png', 'image56.png', 'image57.png', 'image58.png', 'image59.png', 'image60.png', 'image61.png', 'image62.png', 'image63.png', 'image64.png', 'image65.png', 'image66.png', 'image67.png', 'image68.png', 'image69.png', 'image70.png', 'image71.png', 'image72.png', 'image73.png', 'image74.png', 'image75.png', 'image76.png', 'image77.png', 'image78.png', 'image79.png', 'image80.png', 'image81.png', 'image82.png', 'image83.png', 'image84.png', 'image85.png', 'image86.png', 'image87.png', 'image88.png', 'image89.png', 'image90.png', 'image91.png', 'image92.png', 'image93.png', 'image94.png', 'image95.png', 'image96.png', 'image97.png', 'image98.png', 'image99.png', 'image100.png'] let random = Math.floor(Math.random() * 100); image.src = images[random]; setInterval(function(){ let random = Math.floor(Math.random() * 100); image.src = images[random]; }, 15000); </script> </body> </html>
You can just name your function, and call it once, before setting the Interval. let image = document.getElementById('image'); let images = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png', 'image6.png', 'image7.png', 'image8.png', 'image9.png', 'image10.png', 'image11.png', 'image12.png', 'image13.png', 'image14.png', 'image15.png', 'image16.png', 'image17.png', 'image18.png', 'image19.png', 'image20.png', 'image21.png', 'image22.png', 'image23.png', 'image24.png', 'image25.png', 'image26.png', 'image27.png', 'image28.png', 'image29.png', 'image30.png', 'image31.png', 'image32.png', 'image33.png', 'image34.png', 'image35.png', 'image36.png', 'image37.png', 'image38.png', 'image39.png', 'image40.png', 'image41.png', 'image42.png', 'image43.png', 'image44.png', 'image45.png', 'image46.png', 'image47.png', 'image48.png', 'image49.png', 'image50.png', 'image51.png', 'image52.png', 'image53.png', 'image54.png', 'image55.png', 'image56.png', 'image57.png', 'image58.png', 'image59.png', 'image60.png', 'image61.png', 'image62.png', 'image63.png', 'image64.png', 'image65.png', 'image66.png', 'image67.png', 'image68.png', 'image69.png', 'image70.png', 'image71.png', 'image72.png', 'image73.png', 'image74.png', 'image75.png', 'image76.png', 'image77.png', 'image78.png', 'image79.png', 'image80.png', 'image81.png', 'image82.png', 'image83.png', 'image84.png', 'image85.png', 'image86.png', 'image87.png', 'image88.png', 'image89.png', 'image90.png', 'image91.png', 'image92.png', 'image93.png', 'image94.png', 'image95.png', 'image96.png', 'image97.png', 'image98.png', 'image99.png', 'image100.png'] randomImage(); setInterval(randomImage, 15000); function randomImage(){ let random = Math.floor(Math.random() * images.length); image.src = images[random]; } <!DOCTYPE html> <html> <body> <div class="center"> <img src="" id="image"> </div> </body> </html> Here is a working snippet with different images let images = [] for(var i = 0; i<= 100; i++){ images.push("https://picsum.photos/300/200?random="+i); } let image = document.getElementById('image'); randomImage(); setInterval(randomImage, 2000); //I have reduced the interval duration function randomImage(){ let random = Math.floor(Math.random() * images.length); image.src = images[random]; } <!DOCTYPE html> <html> <body> <div class="center"> <img src="" id="image"> </div> </body> </html>
You can shorten your code a little by using setTimeout instead of setInterval. In the function you first display the image, and then use setTimeout to call the function again after a delay. In this working example, as I don't have access to your images, I'm populating the images array with images from dummyimage.com, and setting the timeout delay to one second so you can quickly see the results. const image = document.getElementById('image'); const images = []; // Return a random hex color function rndColor() { return Math.floor(Math.random()*16777215).toString(16); } // Get two hex colours and use them // to form a new dummy image, and then // push that image to the images array for (let i = 0; i < 100; i++) { const hex1 = rndColor(); const hex2 = rndColor(); images.push(`https://dummyimage.com/100x100/${hex1}/${hex2}`); } // The main carousel function // Add an image to the image src, and then // call the carousel function after a delay function carousel() { const random = Math.floor(Math.random() * 100); image.src = images[random]; setTimeout(carousel, 1000); } carousel(); <div class="center"> <img src="" id="image"> </div>
if you want to start from image 1 put this line after declaring the images variable: image.src = images[0]; if you want to start from a random image each reload put this line after declaring the random variable: image.src = images[random]; you do this to initiate a value for the image variable because by default it will equal undefined, so the problem with your code is that it was load an empty image container initially alternatively you can just add an image path to the src attribute of the IMG tag in your HTML code, don't worry it will be overwritten each 15 seconds as targeted
how to randomize multiple images in javascript
i am pretty new to javascript (a little over 2 months into my studies) and am starting my first project. the end goal is to have a set of baseball team logo images (right now 6 images but eventually i would like to expand this to more) randomized every time a button is clicked. i had researched on how to do this and came across the fisher yates algorithm used in a while loop, and various uses of random number generation. decided to use the fisher yates. at the moment, my code seems to work. i followed 1 image and i couldn't see a specific pattern. my other concerns are if i can achieve the same functionality using 1 loop and also cleaning up my code so its not so repetitive. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>sports</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="css/main.css"> </head> <body> <div class="container"> <h1>Sports Random</h1> <br> <div class="row"> <div class="col-sm-2"> <img id="team1"src="images\sports\team1.jpg" alt=""></div> <div class="col-sm-2"> <img id="team2"src="images\sports\team2.jpg" alt=""></div> <div class="col-sm-2"> <img id="team3"src="images\sports\team3.jpg" alt=""></div> <div class="col-sm-2"> <img id="team4"src="images\sports\team4.jpg" alt=""></div> <div class="col-sm-2"> <img id="team5"src="images\sports\team5.jpg" alt=""></div> <div class="col-sm-2"> <img id="team6"src="images\sports\team6.jpg" alt=""></div> </div> <br> <button id="button">Random</button> <button id="reset">Reset</button> </div> </div> <script src="js/main.js"></script> </body> </html> var button = document.getElementById("button"); var reset = document.getElementById("reset"); var team1 = document.getElementById("team1"); var team2 = document.getElementById("team2"); var team3 = document.getElementById("team3"); var team4 = document.getElementById("team4"); var team5 = document.getElementById("team5"); var team6 = document.getElementById("team6"); var pics = ["team1.jpg", "team2.jpg", "team3.jpg", "team4.jpg", "team5.jpg", "team6.jpg"]; var teams = [team1, team2, team3, team4, team5, team6]; button.addEventListener("click", function random() { var i = pics.length, rNum, temp; // shuffle pictures using fisher yates while (--i > 0) { rNum = Math.floor(Math.random() * (i + 1)); temp = pics[rNum]; pics[rNum] = pics[i]; pics[i] = temp; } // display images for (var i = 0; i < teams.length; i++) { teams[i].src = "images\\sports\\" + pics[i]; } }); reset.addEventListener("click", function reset() { team1.src = "images\\sports\\team1.jpg"; team2.src = "images\\sports\\team2.jpg"; team3.src = "images\\sports\\team3.jpg"; team4.src = "images\\sports\\team4.jpg"; team5.src = "images\\sports\\team5.jpg"; team6.src = "images\\sports\\team6.jpg"; });
Just add an id to the div class="row" id="parent"> and replace the code like this. var button = document.getElementById("button"); var reset = document.getElementById("reset"); var originalChildren = Array.from(document.getElementById("parent").children); button.addEventListener("click", function random() { var list = document.getElementById("parent"); for (var i = list.children.length; i >= 0; i--) { list.appendChild(list.children[Math.random() * i | 0]); } }); reset.addEventListener("click", function reset() { document.getElementById("parent").innerHTML = ""; for (var i =0 ; i< originalChildren.length; i++) { document.getElementById("parent").appendChild(originalChildren[i]); } }); Additionally, I would also suggest creating the children dynamically then appending them to parent instead of putting them in HTML. But, this is entirely up to you. Modified the code so you don't have to keep the elements in JS side.
Here is a Fiddle that might help you: https://jsfiddle.net/yha6r5sy/1/ You can use list.children to add it to main div
switch from image to random image onclick with JavaScript
I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript… This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see: this is my javascript function pickimg2() { var imagenumber = 2 ; var randomnumber = Math.random(); var rand1 = Math.round((imagenumber-1) * randomnumber) + 1; myImages1 = new Array(); myImages1[1] = "img_01.gif"; myImages1[2] = "img_02.gif"; myImages1[3] = "img_03.gif"; myImages1[4] = "img_04.gif"; myImages1[5] = "img_05.gif"; myImages1[6] = "img_06.gif"; myImages1[7] = "img_07.gif"; myImages1[8] = "img_08.gif"; myImages1[9] = "img_09.gif"; var image = images[rand1]; document.randimg.src = "myImages1"; } there is my html <!DOCTYPE html> <html> <head> <title>mur</title> <link rel="stylesheet" href="style.css"> <link rel="JavaScript" href="script.js"> </head> <body onLoad="pickimg2"> <div class="fenetre"> <img src="img_01.gif" name="randimg" border=0> </div> </body> </html> If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned: <script type="text/javascript" src="script.js"></script> Here's the updated code, check console.log to see the different image urls getting requested. var myImages1 = new Array(); myImages1.push("img_01.gif"); myImages1.push("img_02.gif"); myImages1.push("img_03.gif"); myImages1.push("img_04.gif"); myImages1.push("img_05.gif"); myImages1.push("img_06.gif"); myImages1.push("img_07.gif"); myImages1.push("img_08.gif"); myImages1.push("img_09.gif"); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function pickimg2() { document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)]; } <div class="fenetre"> <a href="#" onClick="pickimg2();return false;"> <img src="img_01.gif" name="randimg" border=0> </a> </div>
this code bellow is working. I hope it's what you were asking for var images = [ "http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg", "http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg", "http://www.pnas.org/site/misc/images/16-01910.500.jpg" ]; init(); function random_image(images) { var random = randomize(images); while(images[random] === document.getElementById("image").src){ random = randomize(images) } document.getElementById("image").src = images[random].toString(); } function randomize(array){ return Math.floor((Math.random() * (array.length))); } function init() { document.getElementById("image").addEventListener("click", function(){ random_image(images); }); random_image(images); } <!DOCTYPE html> <html> <head> <title>Bonjour</title> </head> <body > <div class="fenetre"> <img id="image" src="" name="randimg" > </div> </body> </html>
Cycle pictures using an array in JS and HTML
this works on a button click and that is how it is meant to be. The problem lies in the fact that it uses hidden images, instead of images stored in an array. Could you please show me how to do it so that it is images stored in an array. <!doctype html> <html> <body> <div id="splash"> <img src="TrafficLightRed.gif" alt="" id="mainImg"> </div> <div id="wrapper"> <div> <button id="clickme" onclick="changeLight();">Click to change</button> <img src="TrafficLightRed.gif" hidden> <img src="TrafficLightYellow.gif" hidden> <img src="TrafficLightGreen.gif" hidden> </div> </div> <script> function changeLight() { var currentImg = document.getElementById("mainImg"); for(var i=1;i<3;i++) { if(document.images[i].src == currentImg.src) { currentImg.src = document.images[i + 1].src; return; } } currentImg.src = document.images[1].src; } </script> </body> </html>
You would store the image's src in an array: imagesArray = ["TrafficLightRed.gif","TrafficLightYellow.gif","TrafficLightGreen.gif" ]; And use the array in place of document.images[i + 1].src: ... for(var i=0;i<imagesArray.length;i++) { if(imagesArray[i] == currentImg.src) { currentImg.src = imagesArray[i]; return; } } ...
This should do the work: ... <script> var images = ["TrafficLightRed.gif", "TrafficLightYellow.gif", "TrafficLightGreen.gif"]; var currentIndex = 0; function changeLight() { var currentImg = document.getElementById("mainImg"); currentImg.src = images[(currentIndex++) % images.length]; } </script> ... Now you can add more images to array images and it will automatically loop through this array.
Evaluating a URL with JavaScript
I wrote a webpage that displays a slideshow of different images that users can look through. However, I need to write a function so if they click on a URL that says http://www.slideshow.com/image3 The slideshow will automatically show "Image 3" in the slideshow when the page is loaded. I have researched this for days, trying to use AJAX, ASP, and various jQuery and .js files, but nothing I have researched seems to fit my purpose. Is there a simpler way to do this with just JavaScript? <!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>Slideshow</title> <script type="text/javascript"> //preloading all the images into a cache //to add more slides, add extra variable declarations var img1 = new Image() img1.src = "img/1.jpg" var img2 = new Image() img2.src = "img/2.jpg" var img3 = new Image() img3.src = "img/3.jpg" var img4 = new Image() img4.src = "img/4.jpg" var img5 = new Image() img5.src = "img/5.jpg" var img6 = new Image() img6.src = "img/6.jpg" var img7 = new Image() img7.src = "img/7.jpg" var img8 = new Image() img8.src = "img/8.jpg" var img9 = new Image() img9.src = "img/9.jpg" var imgNum = 1 var x = 0 var width //function that cycles through different images function slideshow() { if (!document.images) return if (imgNum < 9) // <-- If you add or subtract images in the slideshow, you need to change this number to the amount of imgNum++ //images in the slideshow so it will loop correctly. else imgNum=1 document.images.slide.src=eval("img" + imgNum + ".src") } //function that crops the slideshow image to the screen size and centers it function crop() { if (document.getElementById("slide").width > screen.width) { width = document.getElementById("slide").width width = -1*((width - screen.width)/2) document.getElementById("slide").style.marginLeft= width +"px" document.getElementById("slide").style.marginRight= width + "px" } } //function that evaluates a number passed to it and returns the corresponding image in /img function imgSelect(x) { imgNum = x document.images.slide.src=eval("img" + imgNum + ".src") } //function that hides or shows the menu function hide(object) { if (object.style.display=="none") object.style.display="block" else object.style.display="none" } //function that changes the menu text from "hide menu" to "show menu" and vice versa function menuChange(object) { if (object.innerHTML=="hide menu") object.innerHTML="show menu" else object.innerHTML="hide menu" } //function that allows a link to do both the hide(object) function and the menuChange(object) function with once click function doBoth(object1, object2) { hide(object1) menuChange(object2) } </script> </head> <body onload="crop()"> <center> <div style="background-color:#87D300; padding:5px;"> <a id="button" href="javascript:doBoth(document.getElementById('menu'),document.getElementById('button'))" style="color:#FFFFFF">hide menu</a> </div> </center> <img src="img/logo.png"/> <div id="title"> <h1 style="position:relative; top:-31px; right:-133px">Slideshow</h1> </div> <div id="menu" class="margin"> <h2>Designs</h2> <ul> <li>Splash Page:1</li> <li>Splash Page:2</li> <li>Splash Page:3</li> <li>Splash Page:4</li> <li class="new">Book: 1</li> <li>Book: 2</li> <li>Book: Rollover</li> <li>Book: Clicked</li> <li>Book: Clicked, no Email</li> </ul> </div> </br> <center> <div id="mySlides" style="width:screen.width; overflow:hidden;"> <img src="img/1.jpg" onclick="slideshow()" id="slide"/> </div> </center> </body> </html>
Use a URL hash instead: http://www.slideshow.com#image3 The value will be document.location.hash, which you can use for read/write. Any other manipulation of the URL will cause a navigation event.