image sequence animation load only once not infinitely - javascript

below is my code,In this 1 to 15 image and this image load one by one to 15 and again start from 1 to 15 in specific time interval. In this sequence images play infinitely when page is load but i want images play at only once when page is load.
and I can't fixed this bug please help me out to solve this problem.
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png">
</div>

#pratik, this should help you:
You should use clearInterval like below:
if(j === 15) {
clearInterval(interval);
}
Example
onload = function startAnimation() {
var animDiv = document.getElementById('animation');
var x = document.createElement("IMG");
x.setAttribute("id", 'test');
x.setAttribute("src",
"http://jumpingfishes.com/dancingpurpleunicorns/charging01.png");
animDiv.appendChild(x);
var i = 1,
j = 2;
var interval = setInterval(function () {
var y = (i < 10) ? '0' + i.toString() : i.toString(),
z = (j < 10) ? '0' + j.toString() : j.toString(),
url = document.getElementById('test').src;
document.getElementById('test').src = url.replace(y, z);
i++;
j++;
if (j === 16) {
clearInterval(interval);
}
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
</div>

You should use clearInterval();
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var myInterval=setInterval(function () {
if(i==frameCount-2){
clearInterval(myInterval);
}
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png" />
</div>

You have to clear your interval once you want it to stop running. Using clearInterval().
Check this example:
Note that intervalEnd is the number that once the i reaches it, will clear your interval.
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var intervalEnd = 100;
var intervalId = setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
if (i >= intervalEnd)
clearInterval(intervalId)
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png" />
</div>

Related

simple picture over picture in html

im trying to build a website, where u click on a text, and a picture appears, when you click on this picture, the next one appears and so on. If you reach the last picture, the first one should appear if you click on it. My code is very complicated and it does not work with the last picture. I hope somebody can help me!
<head>
<script type="text/javascript">
function showImage() {
document.getElementById('loadingimage').style.visibility="visible";
}
function showImage2() {
document.getElementById('loadingimage2').style.visibility="visible";
}
function showImage3() {
document.getElementById('loadingimage3').style.visibility="visible";
}
</script>
</head>
<body>
<a onclick="showImage()">Hier clicken</a>
<img onclick="showImage2()" id="loadingimage" src="pic/pic1.jpg" alt="" style="visibility:hidden"></img>
<img onclick="showImage3()" id="loadingimage2" src="pic/pic2.jpg" alt="" style="visibility:hidden"></img>
<img onclick="showImage4()" id="loadingimage3" src="pic/pic3.jpg" alt="" style="visibility:hidden"></img>
</body>
For simplicity, the button will be hidden after you click the first time on the button.
let start = 0,
total = 3,
hasStarted = false;
const images = [...document.querySelectorAll(".image")];
const button = document.querySelector("button");
function showImage() {
if (!hasStarted) {
button.classList.add("hide")
hasStarted = !hasStarted;
}
images.forEach(image => {
if (image.classList.contains("show")) {
image.classList.remove("show");
image.classList.add("hide");
}
})
document.querySelector(`.image${start}`).classList.add("show");
++start;
start = start % total;
}
images.forEach(image => {
image.addEventListener("click", showImage)
})
.hide {
visibility: hidden;
}
.show {
visibility: visible;
}
<button onclick="showImage()">Hier clicken</button>
<img class="image image0 hide" id="loadingimage1" src="https://source.unsplash.com/random/200x200" alt=""></img>
<img class="image image1 hide" id="loadingimage2" src="https://source.unsplash.com/random/200x200" alt=""></img>
<img class="image image2 hide" id="loadingimage3" src="https://source.unsplash.com/random/200x200" alt=""></img>
I feel this is what you need:
<head>
<script type="text/javascript">
function showImage() {
document.getElementById('loadingimage').style.visibility = "visible";
document.getElementById('loadingimage').style.position = 'absolute';
}
function showImage2() {
document.getElementById('loadingimage2').style.visibility = "visible";
document.getElementById('loadingimage2').style.zIndex = '10';
document.getElementById('loadingimage2').style.position = 'absolute'
}
function showImage3() {
document.getElementById('loadingimage3').style.visibility = "visible";
document.getElementById('loadingimage3').style.zIndex = '15';
document.getElementById('loadingimage3').style.position = 'absolute'
}
function showImage4() {
document.getElementById('loadingimage').style.zIndex = '20';
}
</script>
</head>
<body>
<a onclick="showImage()">Hier clicken</a>
<img onclick="showImage2()" id="loadingimage" src="https://source.unsplash.com/random/200x201" alt="" style="visibility:hidden">
<img onclick="showImage3()" id="loadingimage2" src="https://source.unsplash.com/random/200x202" alt="" style="visibility:hidden">
<img onclick="showImage4()" id="loadingimage3" src="https://source.unsplash.com/random/200x203" alt="" style="visibility:hidden">
</body>

Next/prev button for modal with Javascript

I have been trying to make modal for a custom site I'm building. Everything seemed to go fine. It displayed whichever picture I clicked on and "previous" button works as intended. However, there seems to be a problem with "next" button because it behaves differently depending on which picture I'm currently on. Sometimes it jumps by few indexes forward or even backwards. Some insight would be appreciated. Thanks in advance. Here is a code HTML:
<div id="modalcontainer" class="displaynone">
<h4>
<span id="close">X</span>
</h4>
<img src="" alt="" id="modalcontent">
<div class="buttoncontainer">
<div class="previous">
<span id="prev"><</span>
</div>
<div class="next">
<span id="next">></span>
</div>
</div>
</div>
<div id="imgcontainer">
<img src="images/1.JPG" alt="">
<img src="images/2.JPG" alt="">
<img src="images/3.JPG" alt="">
<img src="images/4.JPG" alt="">
<img src="images/8.png" alt="">
<img src="images/9.jpg" alt="">
<img src="images/10.jpg" alt="">
</div>
And JS:
const modalContainer = document.getElementById("modalcontainer");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
const closeModal = document.getElementById("close");
const modalContent = document.getElementById("modalcontent");
const imgContainer = document.getElementById("imgcontainer");
let containerImages = imgContainer.querySelectorAll("img");
let imgIndex = 0;
containerImages.forEach(function(img){
img.setAttribute("data-index", imgIndex++);
img.addEventListener("click", () => {
if(modalContainer.classList.contains("displaynone")){
modalContainer.classList.remove("displaynone");
modalContainer.classList.add("displaymodal");
modalContent.src = img.src;
};
imgIndex = img.dataset.index;
console.log(imgIndex);
});
});
closeModal.addEventListener("click", () => {
if(modalContainer.classList.contains("displaymodal")){
modalContainer.classList.remove("displaymodal");
modalContainer.classList.add("displaynone");
}
imgIndex = 0;
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % containerImages.length;
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
prevButton.addEventListener("click", () => {
imgIndex = (imgIndex -= 1);
if (imgIndex < 0) {
imgIndex = containerImages.length - 1;
console.log(imgIndex);
};
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
I dummied up some objects to get it to run and your previous/next button code seems to work. It there some other code that might be involved? Something modifying the number of images in the imageContainer?
const prevButton = document.querySelector("#prev");
const nextButton = document.querySelector("#next");
let images = document.querySelectorAll("img");
let imgIndex = 0;
images.forEach((img) =>
img.addEventListener("click", () => {
imgIndex = parseInt(img.dataset.index);
setSelected();
})
);
setSelected();
prevButton.addEventListener("click", () => {
imgIndex = imgIndex -= 1;
if (imgIndex < 0) imgIndex = images.length - 1;
setSelected();
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % images.length;
setSelected();
});
function setSelected() {
images.forEach((img) => img.classList.remove("selected"));
images[imgIndex].classList.add("selected");
}
img {
display: inline-block;
border: 2px solid transparent;
}
.selected {
border: 2px solid red;
}
<div id="imageContainer">
<img src="https://picsum.photos/100?random=1" data-index="0">
<img src="https://picsum.photos/100?random=2" data-index="1">
<img src="https://picsum.photos/100?random=3" data-index="2">
<img src="https://picsum.photos/100?random=4" data-index="3">
</div>
<div>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>

How do I make a function that reset the game on click

I am working on a rock paper scissor game. I'm very new to javascript and only know the basics. The code is a little sloppy. What I want is to be able to continue playing the game after a choice is selected. For example, right now if I click rock, the CPU will randomize a result, but then if I click on paper, the result will stay on the screen and the new result will overlap the old one.
I was thinking of adding another condition to the if statements. Also, I was thinking of adding another function to the return of the if statement that might reset it.
html
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
js
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
function cpuChoice() {
const rand = Math.random()
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
} else {
cpuScissors.style.display = 'inline-block'
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice))
css
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
position: absolute;
height: 11rem;
}
Firstly, you need to remove position: absolute; for img which was causing the overlapping.
Secondly, each time you call cpuChoice(), you need to hide the previous element before showing the current element.
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let currentItem;
function cpuChoice() {
const rand = Math.random();
if (currentItem) {
currentItem.style.display = 'none';
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block';
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block';
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block';
currentItem = cpuScissors;
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice));
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
height: 5rem;
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
You don't need all those IDs and Classes.
Use Indexes!
Using indexes you can also retrieve the winner
See this answer: https://stackoverflow.com/a/53983473/383904
const moves = ["Rock", "Paper", "Scissors"],
messages = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
score = [0, 0, 0], // [PL, AI, draw]
ELS = sel => document.querySelectorAll(sel),
EL_result = ELS("#result")[0],
EL_PLScore = ELS("#PLScore")[0],
EL_AIScore = ELS("#AIScore")[0],
ELS_ai = ELS(".ai");
function game() {
const PL = +this.dataset.user; // Get played index as integer
const AI = ~~(Math.random() * 3); // All you need: 0, 1, 2
const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw
score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
EL_result.innerHTML = `You: ${moves[PL]}, AI: ${moves[AI]}, ${messages[result]}`;
EL_PLScore.textContent = score[0];
EL_AIScore.textContent = score[1];
ELS_ai.forEach(el => el.classList.remove('inline-block')); // Hide all
ELS_ai[AI].classList.add('inline-block'); // Show one
}
// EVENTS:
document.querySelectorAll("[data-user]").forEach(el => el.addEventListener("click", game));
.ai {
display: none;
}
.ai.inline-block {
display: inline-block
}
<div class="main-container">
<div class="score">
<span>You: <span id="PLScore">0</span></span>
<span>Computer: <span id="AIScore">0</span></span>
</div>
<div class="user-choice">
<img data-user="0" src="//placehold.it/50x50/888?text=ROCK">
<img data-user="1" src="//placehold.it/50x50/eee?text=PAPER">
<img data-user="2" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div class="cpu-result">
<img class="ai" src="//placehold.it/50x50/888?text=ROCK">
<img class="ai" src="//placehold.it/50x50/eee?text=PAPER">
<img class="ai" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div id="result"></div>
</div>

JavaScript ReferenceError: x is not defined

I am trying to build a webpage to display some images and when clicked with pop-up a modal with thumbnail images at the bottom. I referenced w3Schools to create this and modified it a bit but now recieve a ReferenceError: currentImg is not defined in the console. When I click on an image the modal pops up but the image does not change when the arrows are clicked. Requesting help to understand the error and how to fix it. Please find below my code.
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showImgs(slideIndex);
function plusImg(n) {
showImgs(slideIndex += n);
}
function plusImg(n) {
showImgs(slideIndex = n);
}
function showImgs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > x.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = x.length;
}
alert(x.length)
for (i = 0; i < x.length; i++) {
alert(i)
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
}
x[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " w3-opacity-off";
captionText.innerHTML = dots[slideIndex - 1].alt;
}
.s4 img {
height: 413px;
width: 319px;
margin: 0px;
cursor: pointer;
}
#myModal span {
cursor: pointer;
}
.w3-content {
max-width: 1200px;
}
.w3-content .mySlides {
width: 100%;
}
.w3-content .w3-col {
padding: 5px;
}
.demo {
width: 100%;
}
<head>
<title>Commander, Carrier Strike Group ELEVEN (CCSG 11) Fact Sheet</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
</head>
<body>
<div class="w3-container">
<div class="w3-row-padding">
<div class="w3-col s4">
<img src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page1.jpg" onclick="openModal();currentImg(1)" class="w3-hover-shadow">
<img src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page2.jpg" onclick="openModal();currentImg(2)" class="w3-hover-shadow">
<img src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page3.jpg" onclick="openModal();currentImg(3)" class="w3-hover-shadow">
<img src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page4.jpg" onclick="openModal();currentImg(4)" class="w3-hover-shadow">
<img src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page5.jpg" onclick="openModal();currentImg(5)" class="w3-hover-shadow">
</div>
</div>
<div id="myModal" class="w3-modal w3-black" style="display: block;">
<span class="w3-text-white w3-xxlarge w3-hover-text-grey w3-container w3-display-topright" onclick="closeModal()">×</span>
<div class="w3-modal-content">
<div class="w3-content">
<img class="mySlides" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page1.jpg" style="display: block;">
<img class="mySlides" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page2.jpg" style="display: none;">
<img class="mySlides" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page3.jpg" style="display: none;">
<img class="mySlides" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page4.jpg" style="display: none;">
<img class="mySlides" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page5.jpg" style="display: none;">
<div class="w3-row w3-black w3-center">
<p id="caption">Page 1</p>
<span class="w3-display-left w3-btn" onclick="plusImg(-1)"><</span>
<span class="w3-display-right w3-btn" onclick="plusImg(1)">></span>
</div>
<div class="w3-col s4">
<img class="demo w3-opacity w3-hover-opacity-off w3-opacity-off" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page1.jpg" onclick="currentImg(1)" alt="Page 1">
</div>
<div class="w3-col s4">
<img class="demo w3-opacity w3-hover-opacity-off" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page2.jpg" onclick="currentImg(2)" alt="Page 2">
</div>
<div class="w3-col s4">
<img class="demo w3-opacity w3-hover-opacity-off" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page3.jpg" onclick="currentImg(3)" alt="Page 3">
</div>
<div class="w3-col s4">
<img class="demo w3-opacity w3-hover-opacity-off" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page4.jpg" onclick="currentImg(4)" alt="Page 4">
</div>
<div class="w3-col s4">
<img class="demo w3-opacity w3-hover-opacity-off" src="https://www.public.navy.mil/surfor/ccsg11/PublishingImages/FactSheet_Page5.jpg" onclick="currentImg(5)" alt="Page 5">
</div>
</div>
</div>
</div>
</div>
</body>
You have 2 functions with name plusImg.
Just rename second one to currentImg
function plusImg(n) {
showImgs(slideIndex += n);
}
function plusImg(n) {
showImgs(slideIndex = n);
}
There are some issues in your javascript codes:
there is missing function for currentImg
function currentImg(n) {
console.log(n);
showImgs(n);
}
there is duplicate plusImg function, please remove the 2nd one
there is error in showImgs function, please check my update js codes
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showImgs(slideIndex);
function plusImg(n) {
showImgs(slideIndex += n);
}
function currentImg(n) {
console.log(n);
showImgs(n);
}
function showImgs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (!x.length) return;
slideIndex = n;
if (n > x.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = x.length;
}
console.log(x.length)
for (i = 0; i < x.length; i++) {
console.log(i)
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
}
x[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " w3-opacity-off";
captionText.innerHTML = dots[slideIndex - 1].alt;
}
BTW, I changed alert to console.log for better debug experience. I also added the style
.mySlides {display:none}
Please check. Hope above helps.

Frame by frame animation with Javascript

I'm doing a frame by frame animation with Javascript by animating a sequence of images.
The code for the animation is quite simple.
My problem is, there can be a lot of images, presently 200 but can be up to 1000. Loading the images simultanely can take some times. I'd like to play the animation with 30 images initially and preload the remain in the background. But sometimes, the images take a time to load thus breaking the animation.
How can I pause the animation with a "buffering" and continue the animation when the next image is available ? Also how to skip the preloading when the images are already cached ? Could use some suggestion to improve the code.
HTML
<div class="video-stream">
<img alt="" src="images/stream/Calque-120.jpg" />
<img alt="" src="images/stream/Calque-121.jpg" />
<img alt="" src="images/stream/Calque-122.jpg" />
<img alt="" src="images/stream/Calque-123.jpg" />
<img alt="" src="images/stream/Calque-124.jpg" />
<img alt="" src="images/stream/Calque-125.jpg" />
<img alt="" src="images/stream/Calque-126.jpg" />
<img alt="" src="images/stream/Calque-127.jpg" />
<img alt="" src="images/stream/Calque-128.jpg" />
<img alt="" src="images/stream/Calque-129.jpg" />
<img alt="" src="images/stream/Calque-130.jpg" />
<img alt="" src="images/stream/Calque-131.jpg" />
<img alt="" src="images/stream/Calque-132.jpg" />
<img alt="" src="images/stream/Calque-133.jpg" />
<img alt="" src="images/stream/Calque-134.jpg" />
<img alt="" src="images/stream/Calque-135.jpg" />
<img alt="" src="images/stream/Calque-136.jpg" />
<img alt="" src="images/stream/Calque-137.jpg" />
<img alt="" src="images/stream/Calque-138.jpg" />
<img alt="" src="images/stream/Calque-139.jpg" />
<img alt="" src="images/stream/Calque-140.jpg" />
<img alt="" src="images/stream/Calque-141.jpg" />
<img alt="" src="images/stream/Calque-142.jpg" />
<img alt="" src="images/stream/Calque-143.jpg" />
<img alt="" src="images/stream/Calque-144.jpg" />
<img alt="" src="images/stream/Calque-145.jpg" />
<img alt="" src="images/stream/Calque-146.jpg" />
<img alt="" src="images/stream/Calque-147.jpg" />
<img alt="" src="images/stream/Calque-148.jpg" />
<img alt="" src="images/stream/Calque-149.jpg" />
</div>
CSS
.video-stream
{
position: relative;
}
.video-stream img
{
display: none;
height: auto;
left: 0;
max-width: 100%;
position: absolute;
top: 0;
vertical-align: top;
}
Javascript
var current = 0, // current playing image index
next = 1, // next image index to play
interval = 60, // animation speed
hide_delay = 1, // Delay to hide the current image
img_num = 200, // Total number of image
pack = 10, // Images being preloaded simultanely
idx_start = 149, // The images are index-suffixed so this is the index of the first image to preload
idx_end = 300; // index of the last image in the sequence
var load_more = function()
{
if(idx_start < idx_end)
{
// Preloading images
var temp = [],
temp_html = '';
for(var i = 0; i < pack && idx_start < idx_end; i++)
{
temp[i] = 'images/stream/Calque-' + (++idx_start) + '.jpg';
}
preloadPictures(temp, function()
{
$.each(temp, function(i, v)
{
temp_html += '<img src=' + v + ' />';
});
// Inject into dom
$('.video-stream').append(temp_html);
});
}
}
var play_stream = function()
{
$('.video-stream').find('img').eq(current).delay(interval).fadeOut(hide_delay)
.end().eq(next).delay(interval).hide().fadeIn(hide_delay, play_stream);
if(next < img_num - 1)
{
next++;
}
else
{
next = 0;
}
if(current < img_num - 1)
{
current++;
}
else
{
current = 0;
}
// Background preload
if(idx_start < idx_end)
{
load_more();
}
};
$(window).load(function()
{
play_stream();
});
This is a tricky way of doing it but here it is. You just need an array of images to pass through instead of my count;
var count = 0;
var buffer = 1;
var Vbuffer = 2;
setInterval(function() {
$('#img .' + buffer).prop('src', 'https://placeholdit.imgix.net/~text?txtsize=33&txt=' + count + '&w=150&h=150');
buffer = buffer % 3 + 1;
$('#img img').not('.' + Vbuffer).hide();
$('#img .' + Vbuffer).show();
Vbuffer = Vbuffer % 3 + 1;
count++;
}, 1000);
var buffer2 = 1;
var Vbuffer2 = 2;
var arrayOfImg = ['https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=150&h=150',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=150&h=150',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=150&h=150',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=150&h=150',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=five&w=150&h=150'
]
var count2 = 0;
var arrayCount = arrayOfImg.length;
setInterval(function() {
$('#img2 .' + buffer2).prop('src', arrayOfImg[count2]);
buffer2 = buffer2 % 3 + 1;
$('#img2 img').not('.' + Vbuffer2).hide();
$('#img2 .' + Vbuffer2).show();
Vbuffer2 = Vbuffer2 % 3 + 1;
count2 = (count2 + 1) % arrayCount;
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
wait 3 seconds while the buffer loads
<div id='img'>
<img src='' class='1' />
<img src='' class='2' />
<img src='' class='3' />
</div>
<div id='img2'>
<img src='' class='1' />
<img src='' class='2' />
<img src='' class='3' />
</div>
EDIT
Added arrays to the results, so you can pass in an array of img sources to role through.

Categories

Resources