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
Related
So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}
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>
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>
In a given database using MYSQL, I am storing image file paths to be displayed. I retrieve the path using a query. The returned value is stored in a 'var' type variable. How can I use this as input to the img src attribute to display the image?
For Example:
var x = "http://www.w3schools.com/jsref/compman.gif";
<img src=x>
I am not able to use the above, so is there a way to display the image?
Thanks in advance.
You can create a new image in Javascript using the Image Constructor.
var x = "http://www.w3schools.com/jsref/compman.gif";
var myImage = new Image();
myImage.src = x;
document.body.appendChild(myImage);
Try this code :
var x = "http://www.w3schools.com/jsref/compman.gif";
document.getElementById("YOUR_IMAGR_ID").src = x;
You can create the image tag dynamically in javascript
Javascript Code
function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "http://www.w3schools.com/jsref/compman.gif");
x.setAttribute("width", "304");
x.setAttribute("width", "228");
x.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(x);
}
HTML Code
<body>
<button onclick="myFunction()" >Display Image</button>
</body>
Please check the demo
check this out:
function set(){
document.getElementById('tmp').style.visibility = "visible";
var x = "http://www.w3schools.com/jsref/compman.gif";
document.getElementById("tmp").src = x;
}
<img src="" id="tmp" style="visibility:hidden">
<input type="button" onclick="set();" value="Click Me!">
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.