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)];
Related
The image is not get loaded by this code any improvement needed?
image url is stored into array for accessing that we required something?
<script>
var images = ["lap2.png", "lap1.png", "tv1.png", "tv2.png"];
var i;
function slides() {
for (i = 0; i < 4; i++) {
setInterval(function() {
document.getElementById('slider').src = "" + images[i];
}, 8000);
}
}
</script>
<!--HTML CODE-->
<p id="slide"><img src="lap1.png" id="slider" onload="this.onload=null;
this.src=slides();" multiple>
</p>
var images = ["1.png", "2.png", "3.png", "4.png"];
let i=0;
setInterval(function() {
i = i < images.length -1 ? i + 1 : 0;
document.getElementById('slide').src = `http://placehold.it/300x150?text=${images[i]}`;
}, 1000);
<img id="slide" src="http://placehold.it/300x150?text=1.png"></img>
I've been wrestling with a timing issue in my code for a few nights now, and can't come up with the correct solution.
Psuedo code description:
//event listener on button trigger a die roll each time it is clicked
// call animation function
//generate random values x number of times
//display each result with setTimeout
//run code to determine final "settled upon" value and display results
HTML:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<head>
<title>Make Cards</title>
</head>
<body>
<p>Total:<span id="total"></span></p>
<div id="contain">
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<br>
<button id="rollBtn">Roll</button>
<input type="number" value = "1" min="1" max="6" id = "numDice">
</div>
</body>
</html>
Javascript:
var diceValue = ["⚀", "⚁", "⚂", "⚃", "⚄",
"⚅"];
var dice = document.querySelectorAll(".die");
// select number of dice
var numDice = document.querySelector("#numDice");
// convert string to value
var newNumDice = Number(numDice.value);
var roll = document.querySelector("#rollBtn");
var total = document.querySelector("#total");
// make animation function
// call animation function
init();
function init(){
displayDice();
}
//THIS IS THE BUTTON LISTERNER
roll.addEventListener("click", function(){
//THIS SHOULD RUN BEFORE THE REST OF THE FUNCTION (BUT DOESN'T SEEM TO)
animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value+1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++){
dice[i].style.color = "black";
}
})
numDice.addEventListener("click", function(){
total.innerHTML = "-";
newNumDice = Number(numDice.value);
resetDice();
displayDice();
// console.log(Number(numDice.value));
})
function resetDice(){
for (var i = 0; i < diceValue.length; i++){
dice[i].innerHTML = "";
}
}
// only display chosen number of dice
function displayDice(){
for (var i = 0; i < newNumDice; i++){
dice[i].innerHTML = diceValue[i];
}
}
function generateRandomDice(){
var dieSide = Math.floor(Math.random() * 6);
return dieSide;
}
//ATTEMPT AT WRITING CODE FOR ANIMATION
function animate(){
for (var i = 0; i < 50000; i++){
var ani = setTimeout(rolling, 650);
}
}
function rolling(){
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
dice[i].style.color = "grey";
}
}
Not sure what is going on, but it appears to me that the animate(); code is not run until the rest of eventListener is finished. Any help is great, thank you.
The issue is that you are waiting for asynchronous code to finish before you execute synchronous code. Every time you call setTimeout, it is storing the function to call for when it's ready to be called (which is 650 ms from 'now'!).
To fix, you can await for your animation to finish. Here's how I got it working on your codepen:
Change animate to:
function animate() {
return new Promise((resolve, reject) => {
for (let i = 0; i < 50000; i++) {
setTimeout(() => {
rolling();
if(i == 49999)
resolve();
}, 650);
}
});
}
and then you can await for the Promise to resolve by changing your click listener to this:
roll.addEventListener("click", async function() {
await animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++) {
var value = generateRandomDice();
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value + 1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++) {
dice[i].style.color = "black";
}
});
The result showing afterward was correct for me.
Hope that helps!
Can anyone help me to get this (https://jsfiddle.net/hmatrix/v3jncqac/) code to work?
Inentention: I want to create a counter that increases in increments.
My HTML:
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
My JS:
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() + str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
<script>
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() +
str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
</script>
JSFIDDLE: https://jsfiddle.net/v3jncqac/32/
Your onload function cannot find the function because your js is in a different file. you need to add script src on top of html or do it as shown above.
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>
So I got multiple divs with different images embedded. Each one has its unique name attributes. I'm trying to apply the hover effect to each divs by changing the image source. I don't want to write multiple scripts, rather I'm trying to write a just one block of script that would effect every div.
<div id="div1" >
<img id="img1" name="img1" src="img1_up.jpg" />
</div>
<div id="div2">
<img id="img2" name="img2" src="img2_up.jpg" />
</div>...and so on
Now here is the script that I currently have for the rollover effects
<script>
var var1 = document.getElementById("div1");
var1.addEventListener("mouseover", changeImage1);
var1.addEventListener("mouseout", restoreImage1);
function changeImage1() {
document.getElementById("img1").src = "img1_ro.jpg";
}
function restoreImage1() {
document.getElementById("img1").src = "img1_up.jpg";
}
var var2 = document.getElementById("div2");
var2.addEventListener("mouseover", changeImage2);
var2.addEventListener("mouseout", restoreImage2);
function changeImage2() {
document.getElementById("img2").src = "img2_ro.jpg";
}
function restoreImage2() {
document.getElementById("img2").src = "img2_up.jpg";
}...and so on
</script>
I would like to use the name attributes from each images to create dynamic code to apply to all images. Here is what I have in mind but not sure the exact way to write it. PLEASE HELP
...
var dynamicVar = ????
dynamicVar.addEventListener("mouseover", changeImage();
dynamicVar.addEventListener("mouseout", restoreImage();
function changeImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_ro.jpg";
}
function restoreImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_up.jpg";
}
You can use loop to add event, don't need to specify id for each div:
var inputs = document.getElementsByTagName("div");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf('div') >= 0) {
inputs[i].addEventListener("mouseover", changeImage);
inputs[i].addEventListener("mouseout", restoreImage);
}
}
function changeImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_ro.jpg";
}
function restoreImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_up.jpg";
}
See on fiddle: Link
try this
var parent = document.getElementById("parent");
var childs = parent.getElementsByTagName('div');
for (var i = 0; i < childs.length; i++) {
(function () {
var e = childs[i];
e.addEventListener("mouseover", function () {
changeImage(e);
});
e.addEventListener("mouseout", function () {
restoreImage(e);
});
}());
}
function changeImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
alert(imgs[i].id);
}
}
function restoreImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = img_ro;
}
}
you can check this fiddle