Simplify JS code using Nuxt.js not working - javascript

I have a photo gallery in JavaScript, using Nuxt.js. In the photo gallery, it get the images and (on click), display them in full screen. Everything is working well, but my code is not really good (it can be improved, because it's repetitive). Here is my actual JS, SCSS and Vue code :
window.addEventListener('load', function () {
// Add the photo corresponding to the one in the photo gallery, to the photo gallery full screen
const photo = document.querySelectorAll(".photo");
for (let i = 0; i < photo.length; i++) {
const style = photo[i].currentStyle || window.getComputedStyle(photo[i], false);
const photoBackground = style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
const photoFullscreen = document.querySelectorAll(".photo-fullscreen");
photoFullscreen[i].setAttribute("src", photoBackground);
}
// Open PopUp
const photoGalleryFullscreen = document.querySelector(".photo-gallery-fullscreen");
const imageFullscreen1 = document.querySelector(".slide-container img:nth-child(1)");
const imageFullscreen2 = document.querySelector(".slide-container img:nth-child(2)");
const imageFullscreen3 = document.querySelector(".slide-container img:nth-child(3)");
document.querySelector(".lienImg1").onclick = function() {
photoGalleryFullscreen.style.display = "block";
imageFullscreen1.style.display = "block";
slideIndex = 1;
};
document.querySelector(".lienImg2").onclick = function() {
photoGalleryFullscreen.style.display = "block";
imageFullscreen2.style.display = "block";
slideIndex = 2;
};
document.querySelector(".lienImg3").onclick = function() {
photoGalleryFullscreen.style.display = "block";
imageFullscreen3.style.display = "block";
slideIndex = 3;
};
// Close PopUp
document.querySelector(".out").onclick = function() {
photoGalleryFullscreen.style.display = "none";
imageFullscreen1.style.display = "none";
imageFullscreen2.style.display = "none";
imageFullscreen3.style.display = "none";
slideIndex = 1;
};
});
// Gallery Full Screen
let slideIndex;
function plusSlides(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
let i;
let slides = document.querySelectorAll(".photo-fullscreen");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
// Photo Gallery
.photo-gallery-section {
margin: 50px 0;
.photo-gallery {
width: fit-content;
margin: auto;
display: grid;
grid-template-rows: 250px;
grid-template-columns: repeat(3, 250px);
justify-content: space-between;
gap: 3vw;
.photo:hover {
cursor: pointer;
}
.photo:nth-child(1) {
background: url(../static/images/yoga.jpg) center center / cover;
}
.photo:nth-child(2) {
background: url(../static/images/yoga-2.jpeg) center center / cover;
}
.photo:nth-child(3) {
background: url(../static/images/yoga-3.jpeg) center center / cover;
}
}
.photo-gallery-fullscreen {
display: none;
height: 100vh;
width: 100vw;
background: rgba(0, 0, 0, 0.4);
position: fixed;
top: 0;
left: 0;
z-index: 1;
.slide-container {
width: fit-content;
margin: calc(50vh - 225px) auto;
img {
height: 450px;
z-index: 3;
display: none;
}
}
.prev,
.next {
cursor: pointer;
color: white;
text-shadow: 0.8px 0.8px 4px white;
font-weight: bold;
font-size: 40px;
z-index: 3;
position: absolute;
}
.prev {
margin: calc(50vh - 21px) 0;
margin-left: 15vw;
left: 0;
}
.next {
margin: calc(50vh - 21px) 0;
margin-right: 15vw;
right: 0;
}
.out {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 2;
}
}
}
<section class="photo-gallery-section" id="photo-gallery-section">
<h2 class="photo-gallery-title">Gallerie Photo</h2>
<div class="photo-gallery">
<div class="photo lienImg1"></div>
<div class="photo lienImg2"></div>
<div class="photo lienImg3"></div>
</div>
<div class="photo-gallery-fullscreen">
<a class="prev" onclick="plusSlides(-1, 0)">❮</a>
<a class="next" onclick="plusSlides(1, 0)">❯</a>
<div class="slide-container">
<img class="photo-fullscreen" />
<img class="photo-fullscreen" />
<img class="photo-fullscreen" />
</div>
<div class="out"></div>
</div>
</section>
Now I want to simplify the code but it's not working. Here is the new part of code :
// Open PopUp
const photoGalleryFullscreen = document.querySelector(".photo-gallery-fullscreen");
const imagesFullscreen = document.querySelectorAll(".slide-container img");
for (let i = 0; i < imagesFullscreen.length; i++) {
document.querySelectorAll(".photo").onclick = function() {
photoGalleryFullscreen.style.display = "block";
imagesFullscreen[i].style.display = "block";
slideIndex = i;
}
}
Thank you very much for your help,
Maxime
EDIT : Here is the new code that is working :
// Open PopUp
const photoGalleryFullscreen = document.querySelector(".photo-gallery-fullscreen");
const imagesFullscreen = document.querySelectorAll(".slide-container img");
for (let i = 0; i < imagesFullscreen.length; i++) {
photo[i].onclick = function() {
photoGalleryFullscreen.style.display = "block";
imagesFullscreen[i].style.display = "block";
slideIndex = i;
}
// Close PopUp
document.querySelector(".out").onclick = function() {
photoGalleryFullscreen.style.display = "none";
imagesFullscreen[i].style.display = "none";
slideIndex = 1;
};
}

Related

JS variable have not the value that it should have (with JS, SCSS and Nuxt.js)

I have a photo gallery in JavaScript, using Nuxt.js. The problem is that the variable slideIndex should be equal to a number (defined with the .onclick events), and when we look at this variable in the JS console, we see it as undefined. The consequences are that slideIndex is not a number (NaN), so it not corresponds to an image, and so slides[slideIndex-1].style.display returns a TypeError because it's not possible to know the display of nothing.
Here is the js, scss and vue code :
window.addEventListener('load', function () {
let slideIndex;
// Open PopUp
document.querySelector(".lienImg1").onclick = function() {
document.querySelector(".photo-gallery-fullscreen").style.display = "block";
document.querySelector(".slide-container img:nth-child(1)").style.display = "block";
slideIndex = 1; // slideIndex should be equal to 1, but is not (undefined)
};
document.querySelector(".lienImg2").onclick = function() {
document.querySelector(".photo-gallery-fullscreen").style.display = "block";
document.querySelector(".slide-container img:nth-child(2)").style.display = "block";
slideIndex = 2; // slideIndex should be equal to 2, but is not (undefined)
};
document.querySelector(".lienImg3").onclick = function() {
document.querySelector(".photo-gallery-fullscreen").style.display = "block";
document.querySelector(".slide-container img:nth-child(3)").style.display = "block";
slideIndex = 3; // slideIndex should be equal to 3, but is not (undefined)
};
// Close PopUp
document.querySelector(".out").onclick = function() {
document.querySelector(".photo-gallery-fullscreen").style.display = "none";
document.querySelector(".slide-container img:nth-child(1)").style.display = "none";
document.querySelector(".slide-container img:nth-child(2)").style.display = "none";
document.querySelector(".slide-container img:nth-child(3)").style.display = "none";
slideIndex = 1;
};
});
// Gallery Full Screen
let slideIndex;
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Problem : slideIndex is not defined (undefined) --> it's not a number (NaN) --> it not corresponds to an image --> "slides[slideIndex-1].style.display" returns (TypeError)
function showSlides(n) {
let i;
let slides = document.querySelectorAll(".photo-fullscreen");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
// Photo Gallery
.photo-gallery-section {
margin: 50px 0;
.photo-gallery {
width: 80%;
height: 250px;
margin: auto;
display: grid;
grid-template-rows: 250px;
grid-template-columns: repeat(3, 250px);
justify-content: space-between;
gap: 10px;
.photo:hover {
cursor: pointer;
}
.photo:nth-child(1) {
background: url(https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1820&q=80) center center / cover;
}
.photo:nth-child(2) {
background: url(https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80) center center / cover;
}
.photo:nth-child(3) {
background: url(https://images.unsplash.com/photo-1524863479829-916d8e77f114?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80) center center / cover;
}
}
.photo-gallery-fullscreen {
display: none;
height: 100vh;
width: 100vw;
background: rgba(0, 0, 0, 0.4);
position: fixed;
top: 0;
left: 0;
z-index: 1;
.slide-container {
width: fit-content;
margin: calc(50vh - 225px) auto;
}
.slide-container img {
height: 450px;
z-index: 3;
display: none;
}
.prev,
.next {
cursor: pointer;
color: #333;
font-weight: bold;
font-size: 40px;
z-index: 3;
position: absolute;
}
.prev {
margin: calc(50vh - 21px) 0;
margin-left: 15vw;
left: 0;
}
.next {
margin: calc(50vh - 21px) 0;
margin-right: 15vw;
right: 0;
}
.out {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 2;
}
}
}
<section class="photo-gallery-section" id="photo-gallery-section">
<h2 class="photo-gallery-title">Gallerie Photo</h2>
<div class="photo-gallery">
<div class="photo lienImg1"></div>
<div class="photo lienImg2"></div>
<div class="photo lienImg3"></div>
</div>
<div class="photo-gallery-fullscreen">
<a class="prev" onclick="plusSlides(-1, 0)">❮</a>
<a class="next" onclick="plusSlides(1, 0)">❯</a>
<div class="slide-container">
<img src="https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1820&q=80" />
<img
src="https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80"
class="photo-fullscreen"
/>
<img src="https://images.unsplash.com/photo-1524863479829-916d8e77f114?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80" />
</div>
<div class="out"></div>
</div>
</section>
Thank you very much for your help,
Maxime
let slideIndex in the load event function is local to that (anonymous) function., and shadows the global definition underneath the comment // Gallery Full Screen.
The simplest solution may be to remove the declaration of slideIndex from the load event handler so that the global variable is used by all code.

Clicking stop button in my game does not stop the game as expected

When the game is over, it pops up with button to play again and if you click that button it will redirect you to play button.
If you click play the game should start but the issue when the game is over and it pop up with first box that has play again button and I click it, the game will redirect me to play button and before i click play button the game will start even i didn't click play button.
I called function eggStop() in PLAY_Again button to stop the game but the game didn't stop. and I call the same function at gameOver() function and it worked only in gameOver().
if there is a recommendation about writing code to enhance it, it will be appreciated.
here is images files
https://drive.google.com/drive/folders/1vfvcxs7LHg83SLu6L2iGp5zzMWk5zbwV?usp=sharing
var egg1 = document.getElementById("egg1");
var egg2 = document.getElementById("egg2");
var egg3 = document.getElementById("egg3");
var pos1 = 0;
var pos2 = 0;
var pos3 = 0;
var basket = document.getElementById("basket");
var Y_Pos = 0;
var X_Pos = 0;
var Score = 0;
var Life = 10;
var SCORE1 = document.getElementById("SCORE");
var LIFE1 = document.getElementById("LIFE");
var speed1 = 0;
var speed2 = 0;
var speed3 = 0;
var PLAY_Div = document.getElementById("PLAY-Div");
var PLAY_Again = document.getElementById("PLAY-again");
var caption_Score = document.getElementById("caption-score");
var Play_Btn = document.getElementById("PLAY-btn");
var Home1 = document.getElementById("Home");
var basketScore = document.getElementById("basket-score");
var basket_div = document.getElementById("basket-div");
var L = ""
var S = ""
document.addEventListener("mousemove", function(e) {
basket_div.style.left = e.clientX;
Y_Pos = e.clientY;
X_Pos = e.clientX;
console.log("X_Pos" + X_Pos);
console.log("Y_Pos" + Y_Pos);
})
function eggMove() {
pos1 = pos1 + speed1 + 30;
egg1.style.top = pos1+"px";
console.log("Pos1" + pos1);
pos2 = pos2 + speed2 + 30
egg2.style.top = pos2;
pos3 = pos3 + speed3 + 30;
egg3.style.top = pos3+"px";
floorCollision();
}
function eggStop() {
pos1 = 30;
egg1.style.top = pos1+"px";
pos2 = 30
egg2.style.top = pos2+"px";
pos3 = 30;
egg3.style.top = pos3+"px";
}
PLAY_Again.addEventListener("click", function() {
eggStop(); /* it doesn't work , it can't stop the game/eggs*/
PLAY_Div.style.display = "none";
Home1.style.display = "block";
Life = 10;
speed1 = 0;
speed2 = 0;
speed3 = 0;
Score = 0;
})
Play_Btn.addEventListener("click", function() {
setInterval(eggMove, 500);
Home1.style.display = "none";
Life = 10;
speed1 = 0;
speed2 = 0;
speed3 = 0;
Score = 0;
})
function gameOver(Life) {
if (Life <= 0) {
eggStop();
PLAY_Div.style.display = "block";
caption_Score.innerHTML = Score;
Life = 0;
LIFE1.innerHTML = L + Life;
}
}
function floorCollision() {
gameOver(Life);
if (pos1 >= 470) {
if (120 <= X_Pos && X_Pos <= 275) {
Score++;
speed1 = speed1 + 10;
pos1 = 30;
egg1.style.top = pos1+"px";
egg1.src = "imagess/Happy_Egg.svg"
console.log(Score + "Score1");
basketScore.innerHTML = Score;
} else {
egg1.src = "imagess/Broken_Egg.svg";
setTimeout(function() {
pos1 = 45;
egg1.src = "imagess/Happy_Egg.svg"
egg1.style.top = pos1+"px";
}, 500)
Life = Life - 0.5;
}
}
if (pos2 >= 470) {
if (530 <= X_Pos && X_Pos <= 690) {
Score++;
speed2 = speed2 + 10;
pos2 = 30;
egg2.style.top = pos2+"px";
egg2.src = "imagess/Happy_Egg.svg"
console.log(Score + "Score2");
basketScore.innerHTML = Score;
} else {
egg2.src = "imagess/Broken_Egg.svg";
setTimeout(function() {
pos2 = 45;
egg2.src = "imagess/Happy_Egg.svg"
egg2.style.top = pos2+"px";
}, 500)
Life = Life - 0.5;
}
}
if (pos3 >= 470) {
if (940 <= X_Pos && X_Pos <= 1100) {
Score++;
speed3 = speed3 + 10;
pos3 = 30;
egg3.style.top = pos3+"px";
egg3.src = "imagess/Happy_Egg.svg"
console.log(Score + "Score3");
basketScore.innerHTML = Score;
} else {
egg3.src = "imagess/Broken_Egg.svg";
setTimeout(function() {
pos3 = 45;
egg3.src = "imagess/Happy_Egg.svg"
egg3.style.top = pos3+"px";
}, 500)
Life = Life - 0.5;
}
}
S = "SCORE "
SCORE1.innerHTML = S + Score;
L = "LIFE "
LIFE1.innerHTML = L + Life;
}
body {
background-image: url(../imagess/Background_Night.svg);
background-size: cover;
background-position: center center;
overflow: hidden;
}
#chicken1 {
/* background-color: greenyellow; */
width: 10%;
position: absolute;
top: 10%;
left: 15%;
z-index: 1;
animation: henMove 2s infinite;
}
#chicken2 {
/* background-color: greenyellow; */
width: 10%;
position: absolute;
top: 10%;
left: 45%;
z-index: 2;
animation: henMove 2s infinite;
}
#chicken3 {
/* background-color: greenyellow; */
width: 10%;
position: absolute;
top: 10%;
left: 75%;
z-index: 3;
animation: henMove 2s infinite;
}
#hen1,
#hen2,
#hen3 {
width: 85%;
}
#egg1,
#egg2,
#egg3 {
position: absolute;
left: 35px;
top: 45px;
z-index: -1;
width: 30%;
}
#keyframes henMove {
0% {
width: 150px;
}
50% {
width: 160px;
}
100% {
width: 150px;
}
}
#PLAY-Div {
width: 40%;
/* position: absolute; */
background-color: rgba(0, 0, 0, 0.5);
position: absolute;
height: 300px;
top: 30%;
left: 30%;
z-index: 100;
border-radius: 20%;
display: none;
}
#PLAY-Div h2 {
font-size: 80px;
}
#PLAY-Div button {
font-size: 30px;
}
#Home {
width: 40%;
/* position: absolute; */
background-color: rgba(100, 100, 0, 0.5);
position: absolute;
height: 300px;
top: 30%;
left: 30%;
z-index: 102;
border-radius: 20%;
display: block;
}
#Home h2 {
font-size: 80px;
}
#Home button {
font-size: 30px;
}
#basket-div {
position: relative;
width: 10%;
height: 10%;
top: 550px;
/* background-color: tomato; */
}
#basket {
width: 100%;
position: absolute;
bottom: 50px;
}
#basket-div h3 {
width: 100%;
position: absolute;
color: white;
left: 45%;
bottom: 75%;
z-index: 9999;
}
<!-- Home -->
<div id="Home" class="text-center">
<h2>HAPPY EGGS</h2>
<button id="PLAY-btn" class="btn btn-danger w-25 my-5">PLAY </button>
</div>
<!-- Play-Again -->
<div id="PLAY-Div" class="text-center">
<h2>HAPPY EGGS</h2>
<h2 id="caption-score"></h2>
<button id="PLAY-again" class="btn btn-danger w-25 my-5">PLAY AGAIN</button>
</div>
<!-- Score And Life -->
<div id="dashboard" class="text-white d-flex justify-content-between mx-5">
<h2 id="SCORE">SCORE 0</h2>
<h2 id="LIFE">LIFE 10</h2>
</div>
<!-- Chicken and Egg -->
<!-- <div class="d-flex justify-content-center align-items-center"> -->
<div id="chicken1">
<img id="hen1" src="imagess/Happy_hen.svg">
<img id="egg1" src="imagess/Happy_Egg.svg">
</div>
<div id="chicken2">
<img id="hen2" src="imagess/Happy_hen.svg">
<img id="egg2" src="imagess/Happy_Egg.svg">
</div>
<div id="chicken3">
<img id="hen3" src="imagess/Happy_hen.svg">
<img id="egg3" src="imagess/Happy_Egg.svg">
</div>
<!-- </div> -->
<div id="basket-div">
<h3 id="basket-score">0</h3>
<img id="basket" src="imagess/Basket.svg">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.0/cjs/popper.min.js"></script>
The problem you have is that you don't stop the interval from running, so it keeps going.
eggStop resets the positions, but the move function keeps being called.
To fix this, you'll need to introduce a global variable to track the interval, and cancel it in eggStop.
Put this variable with your other global variables.
var intervalID = 0;
Then in the event handler you add to the Play_Btn click:
intervalID = setInterval(eggMove, 500);
And then in eggStop add:
clearInterval(intervalID);

Why won't display: flex; and justify-content: center; center this slideshow?

I want this slideshow to be centered within its grid-area.
I tried using flexbox on the grid area to center it, but that didn't work.
The img elements need to have position: absolute; so that they can overlap and the fade effect will work. (Unless you can show me another way).
Here is the Javascript that creates the slideshow:
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes;
imgArray = [
'beer buckets.jpg',
"beer and rita's.jpg",
'fried shrimp.jpg',
'beer and bloody mary.jpg',
'tamales.jpg'
];
console.log(slides);
function buildSlideShow(arr) {
for (i = 1; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
}
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
fadeOut(slides[curIndex]);
curIndex++;
if (curIndex === slides.length) {
curIndex = 1;
}
fadeIn(slides[curIndex]);
setTimeout(function() {
slideShow();
}, imgDuration);
};
buildSlideShow(imgArray);
slideShow();
#slider {
position: relative;
}
#slider>img {
border: 2px solid black;
}
#slider img {
transition: opacity 1.5s;
position: absolute;
top: 0;
left: 0;
opacity: 0;
height: 100%;
}
#slider img.fadeIn {
opacity: 1;
height: 100%;
}
<div id='slider'>
</div>

Reset JavaScript interval instead of clearing it

I am working on a custom image carousel, using jQuery and CSS. My aim is to make it really lightweight but with enough features.
The script has an auto feature that I want to be stopped if the user clicks a bullet. I am using clearInterval for this purpose.
I would like to reset that interval, instead of clearing it. In other words, when the user clicks a bullet, I want that interval between two slides to be a "full" one (of 4 seconds).
Here is the code:
var $elm = $('.slider'),
$slidesContainer = $elm.find('.slider-container'),
slides = $slidesContainer.children('a'),
slidesCount = slides.length,
slideHeight = $(slides[0]).find('img').outerHeight(false),
animationspeed = 300,
animationInterval = 4000;
// Set (initial) z-index for each slide
var setZindex = function() {
for (var i = 0; i < slidesCount; i++) {
$(slides[i]).css('z-index', slidesCount - i);
}
};
setZindex();
var displayImageBeforeClick = null;
var setActiveSlide = function() {
$(slides).removeClass('active');
$(slides[activeIdx]).addClass('active');
};
var advanceFunc = function() {
if ($('.slider-nav li.activeSlide').index() + 1 != $('.slider-nav li').length) {
$('.slider-nav li.activeSlide').next().find('a').trigger('click');
} else {
$('.slider-nav li:first').find('a').trigger('click');
}
}
var autoAdvance = setInterval(advanceFunc, animationInterval);
//Set slide height
$(slides).css('height', slideHeight);
// Append bullets
for (var i = 0; i < slidesCount; i++) {
var bullets = '<li>' + i + '</li>';
if (i == 0) {
// active bullet
var bullets = '<li class="activeSlide">' + i + '</li>';
// active slide
$(slides[0]).addClass('active');
}
$('.slider-nav').append(bullets);
};
var slideUpDown = function() {
// set top property for all the slides
$(slides).not(displayImageBeforeClick).css('top', slideHeight);
// then animate to the next slide
$(slides[activeIdx]).animate({
'top': 0
}, animationspeed);
$(displayImageBeforeClick).animate({
'top': "-100%"
}, animationspeed);
};
$('.slider-nav a').on('click', function(event) {
event.preventDefault();
displayImageBeforeClick = $(".slider-container .active");
activeIdx = $(this).text();
if ($(slides[activeIdx]).hasClass("active")) {
return false;
}
$('.slider-nav a').closest('li').removeClass('activeSlide');
$(this).closest('li').addClass('activeSlide');
// Stop autoadvance if user clicks bullet
if (event.originalEvent !== undefined) {
clearInterval(autoAdvance);
}
setActiveSlide();
slideUpDown();
});
body * {
box-sizing: border-box;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.slider {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
.slider .slider-nav {
text-align: center;
position: absolute;
padding: 0;
margin: 0;
left: 10px;
right: 10px;
bottom: 2px;
z-index: 30;
}
.slider .slider-nav li {
display: inline-block;
width: 20px;
height: 3px;
margin: 0 1px;
text-indent: -9999px;
overflow: hidden;
background-color: rgba(255, 255, 255, .5);
}
.slider .slider-nav a {
display: block;
height: 3px;
line-height: 3px;
}
.slider .slider-nav li.activeSlide {
background: #fff;
}
.slider .slider-nav li.activeSlide a {
display: none;
}
.slider .slider-container {
width: 100%;
text-align: center;
}
.slider .slider-container a {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
}
.slider .slider-container img {
transform: translateX(-50%);
margin-left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
<div class="slider slider-homepage">
<ul class="slider-nav"></ul>
<div class="slider-container">
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=east" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=south" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=west" alt="">
</a>
</div>
</div>
</div>
I have not figured out how to do that.
Like #epascarello said in a comment above, just clear & start again:
if (event.originalEvent !== undefined) {
clearInterval(autoAdvance);
autoAdvance = setInterval(advanceFunc, animationInterval);
}
later edit:
If the callback or the interval are not available anymore when restarting, it could help to "save" them in a closure:
function startInterval(func, delay) {
var id = setInterval(func, delay);
return {
stop: function() { clearInterval(id); },
restart: function() { clearInterval(id); id = setInterval(func, delay); }
};
}
var autoAdvance = startInterval(advanceFunc, animationInterval);
//later
autoAdvance.restart();

Clickable bubble control auto slideshow pure JavaScript

How could I link the marked bubble to JavaScript auto slider (window.setInterval(function slideA() { ) ? Check codes to understand this issue. The slides go automatically, but the bubble only react on clicks.
var imagecount = 1;
var total = 3;
function slide(x) {
var Image = document.getElementById('img');
var nodes = document.getElementById('bubbles').getElementsByTagName('div');
for(var i=0; i<nodes.length; i++) {
if(i == imagecount-1) {
nodes[i].style.backgroundColor = '#F86215';
}
else {
nodes[i].style.backgroundColor = 'transparent';
}
}
imagecount = imagecount + x;
if (imagecount > total){ imagecount = 1;}
if (imagecount < 1){ imagecount = total;}
Image.src = "IMAGE/img"+ imagecount +".jpg";
}
window.setInterval(function slideA() {
var Image = document.getElementById('img');
imagecount = imagecount + 1;
if (imagecount > total){ imagecount = 1;}
if (imagecount < 1){ imagecount = total;}
Image.src = "IMAGE/img"+ imagecount +".jpg";
}, 5000);
function selectSlide(slideNumber){
imagecount = slideNumber;
var Image = document.getElementById('img');
Image.src = "IMAGE/img"+imagecount +".jpg";
}
function selectSlide(slideNumber, divid){
var nodes = document.getElementById('bubbles').getElementsByTagName('div');
for(var i=0; i<nodes.length; i++) {
nodes[i].style.backgroundColor = 'transparent';
}
divid.style.backgroundColor = '#F86215';
imagecount = slideNumber;
var Image = document.getElementById('img');
Image.src = "IMAGE/img"+imagecount +".jpg";
}
#img {
width: 100%;
position: relative;
height: auto;
}
.container-fluid {
width: 100%;
height: auto;
position: relative;
}
.container-fluid #left-arrow .left {
width: 60px;
position: absolute;
top: 31%;
left: 0px;
}
.container-fluid #right-arrow .right {
position: absolute;
top: 31%;
right: 0px;
width: 60px;
}
.container #left-arrow .left:hover {
cursor:pointer;
cursor: hand;
}
.container #right-arrow .right:hover {
cursor:pointer;
cursor: hand;
}
#bubbles{
width: 120px;
margin: 0px auto;
text-align: center;
top: 80%;
position: absolute;
left: 45%;
}
#bubbles > div{
display: inline-block;
width: 10px;
height: 10px;
margin: 24px 10px 0px 10px;
background: rgba(0,0,0,.1);
text-align: center;
border: 2px solid #F86215;
border-radius: 100%;
font-size: 19px;
text-decoration: none;
transition: background 0.3s linear 0s;
cursor: pointer;
}
<div class="container-fluid">
<img src="IMAGE/img1.jpg" alt="" id="img"/>
<div id="left-arrow"><img onClick="slide(-1)" class="left" src="IMAGE/arrow-left.png" alt=""/></div>
<div id="right-arrow"><img onClick="slide(1)" class="right" src="IMAGE/arrow-right.png" alt=""/></div>
<div id="bubbles">
<div onclick="selectSlide(1,this)" style="background:#F86215;"></div>
<div onclick="selectSlide(2,this)"></div>
<div onclick="selectSlide(3,this)"></div>
</div>
</div>
Took a while to get a JS only answer working, but here it is!
Updated HTML
<div id="bubbles">
<div class="bubble" onclick="selectSlide(1,this)" style="background:#F86215;"></div>
<div class="bubble" onclick="selectSlide(2,this)"></div>
<div class="bubble" onclick="selectSlide(3,this)"></div>
</div>
Updated Javascript
window.setInterval(function slideA() {
var image = document.getElementById('img');
imagecount = imagecount + 1;
if (imagecount > total) {
imagecount = 1;
}
if (imagecount < 1) {
imagecount = total;
}
image.src = "IMAGE/img" + imagecount + ".jpg";
var bubbles = document.getElementsByClassName("bubble");
var i;
for(i = 0; i < bubbles.length; i++) {
bubbles[i].style.backgroundColor = 'transparent';
}
document.getElementsByClassName("bubble")[imagecount - 1].style.backgroundColor = '#F86215';
}, 5000);
JSFiddle

Categories

Resources