Autoplay in slider with js - javascript

let left = document.querySelector('.left');
let right = document.querySelector('.right');
let img = document.querySelector('.imgs');
let imgs = document.querySelectorAll('img');
let index = 0;
function rightimg() {
right.addEventListener('click', function () {
index++;
if (index > imgs.length - 1) {
index = 0;
}
img.style.transform = `translateX(${-index * 500}px)`;
console.log(img);
});
}
// setInterval(rightimg, 2000);
left.addEventListener('click', function () {
index--;
if (index < 0) {
index = imgs.length - 1;
}
img.style.transform = `translateX(${-index * 500}px)`;
console.log(img);
});
Hi friends,
I want to make autoplay image in this slider but setInterval is not working,
can you say what is wrong in here?
Thank you

Your function adds an eventlistener but it will only work when there will be an event(which is click in this case)
You can use swiperjs, it has many types of features and framework/library implentations. https://swiperjs.com/swiper-api

Related

how to implement click logic

hi everyone!
i have a map with dots MAP which every 3 seconds shows a block with info
a function that is already in progress, and I want the function to stop when clicking on a point and display an infoblock for me(and i did it).
sorry in advance below is my code
// map with dots
var isActive = 0;
var isLoading = 1;
const count = document.querySelectorAll("[data-id]");//circle svg around dot
function removeClass() {
let infoCards = document.querySelectorAll("[data-info-id]");// info page name of the project
infoCards.forEach((el) => {
el.classList.remove("show");
});
}
function removeCircle() {
count.forEach((el) => {
el.style.display = "none";
});
}
function ready() {
function setAround(percent, idx) {
removeCircle();
let beforeElemIdx = idx === 0 ? count.length - 1 : idx - 1;
let beforeElem = document.querySelector(
'[data-id="' + beforeElemIdx + '"]'
);
let elem = document.querySelector('[data-id="' + idx + '"]');
elem.style.display = "block";
elem.classList.remove('active-circle');
beforeElem.style.display = "block";
const math = 2 * Math.PI * elem.r.baseVal.value;
elem.style.strokeDasharray = `${math} 1000`;
let a = math * (1 - percent / 100);
elem.style.strokeDashoffset = a;
if (percent >= 99.5) {
removeClass();
let infoShow = document.querySelector(`[data-info-id="${idx}"]`);
infoShow.classList.add("show");
isLoading++;
if (isLoading === count.length) {
isLoading = 0;
}
}
}
requestAnimationFrame(draw);
function draw(t) {
let idx = isLoading;
requestAnimationFrame(draw);
setAround((t / 30) % 100, idx);//timer 3sec
}
}
document.addEventListener("DOMContentLoaded", ready);
and i did this
var dots = document.querySelectorAll(".dota");
var infoCards = document.querySelectorAll("[data-info-id]");
let circle = document.querySelectorAll('[data-id]');
dots.forEach((el) => {
el.addEventListener('click', () => {
let idx = el.dataset.dota;
let circle = el.dataset.dota;
showInfo(idx);
addCircle(idx);
});
});
function showInfo(idx) {
removeClass();
let elem = document.querySelector(`[data-info-id='${idx}']`);
elem.classList.add('show');
}
function addCircle(idx) {
let circle = document.querySelector(`[data-id='${idx}']`);
circle.classList.add('active-circle');
}
and if u want my site pls dm me i'll send my github page
PUG CODE
TY ALL!
Have you tried making a condition into the drawing function that pauses it?
If it's paused you can call another function that will draw the info of the specific dot only once and then create a condition in which it will resume the drawing normally.
When I used drawing function I've simply added a bool variable that stored if paused or not in the recursive function.

Why does function clearInterval() not working? I used setInterval too

I'm creating a product hover effect where I used mouseover and mouseleave functions. However, I'm currently having problems with the clearInterval function on Javascript.
Do I miss on something? The structure is also aligned.
Here's my code:
<script>
document.addEventListener("DOMContentLoaded", ()=>{
// //get img url from span
// const src = spanElem.attr('data-original');
// //change span to img using the value from data-original
// spanElem.replaceWith('<img class="product-img-toadd w3-animate-fading" src="' + src + '"/>');
const imgGallery = document.querySelectorAll('.product-img-gallery');
const imageDiv = document.querySelectorAll('.product-tile__image');
let interval
imageDiv.forEach(el=>{
//img
const imgGalleryItem = el.querySelectorAll('.product-img-gallery__item')
el.addEventListener("mouseenter", ()=>{
imgGalleryItem.forEach(item=>{
const src = item.getAttribute('data-original')
const img = `<img class="product-img-toadd w3-animate-fading" src="${src}"/>`
item.insertAdjacentHTML('beforeend',img)
//slider
const imgSlides = el.querySelectorAll('.product-img-toadd');
let currentIndex = 0
interval = setInterval(() => {
imgSlides.forEach((item) => {
item.style.opacity = 0;
});
imgSlides[currentIndex].style.opacity = 1;
if (currentIndex === imgSlides.length - 1) {
currentIndex = 0;
} else {
currentIndex = currentIndex + 1;
}
console.log("tick")
}, 750);
})
})
el.addEventListener("mouseleave", ()=>{
const imgSlides = el.querySelectorAll('.product-img-toadd');
imgSlides.forEach((item) => {
item.style.opacity = 0;
});
clearInterval(interval);
})
})
})
You're assiging interval in a loop, overriding each previous element with the next.
A possible solution would be to push each interval to a array, then iterate through all elements and clear it's elements.
let intervals = [];
intervals.push( setInterval(() => { ... });
...
intervals.forEach((iv) => clearInterval(iv));

JavaScript Image Gallery 2

I don't know if this question has been asked before or not. But...
I have the following JavaScript code in my HTML file:
<img id="imageDisplay">
<script type="text/javascript">
var displayImage = document.querySelector( '#imageDisplay' );
var imageArray = [ 'http://www.joongcho.com/Images/30th-Bday-Party-01.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-02.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-03.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-04.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-05.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
displayImage.setAttribute( 'src', imageArray[ imageCount ] );
function nextImage(imageCount) {
}
function previousImage(imageCount) {
}
</script>
I'm trying to put a next Image and a previous Image function for this HTML.
For the next image, if there are more than 1 images and the image is not the last image, then there should be a link that allows a user to click through the array forwards. Also, if the image is the last image in the array, then the link is hidden.
For the previous image, if the image is not the first image of the array, then there should be a link that allows a user click through the array backwards. if the image is the first image, then the previous link should be hidden.
Any help is appreciated.
You have to attach event listeners to buttons or links (I used buttons):
var displayImage = document.getElementById('imageDisplay');
var buttonPrev = document.getElementById('button-prev');
var buttonNext = document.getElementById('button-next');
var imageArray = [ '../Images/30th-Bday-Party-01.jpg',
'../Images/30th-Bday-Party-02.jpg',
'../Images/30th-Bday-Party-03.jpg',
'../Images/30th-Bday-Party-04.jpg',
'../Images/30th-Bday-Party-05.jpg',
'../Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
function nextImage () {
imageCount++;
if (imageCount >= imageLength - 1) {
buttonNext.style.display = 'none';
imageCount = imageLength - 1;
}
if (imageCount < imageLength) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount > 0) {
buttonPrev.style.display = 'inline';
}
}
function previousImage () {
imageCount--;
if (imageCount <= 0) {
buttonPrev.style.display = 'none';
imageCount = 0;
}
if (imageCount >= 0) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount < imageLength) {
buttonNext.style.display = 'inline';
}
}
displayImage.setAttribute('src', imageArray[imageCount]);
displayImage.textContent = imageCount;
buttonPrev.style.display = 'none';
buttonNext.addEventListener('click', nextImage);
buttonPrev.addEventListener('click', previousImage);
<img id="imageDisplay" />
<button id="button-prev">Back</button>
<button id="button-next">Forward</button>
Of course, you can't look at the images yet.

Execute function IF another function is complete NOT when

I am having trouble creating a slider that pauses on hover, because I execute the animation function again on mouse off, if I flick the mouse over it rapidly (thereby calling the function multiple times) it starts to play up, I would like it so that the function is only called if the other function is complete, otherwise it does not call at all (to avoid queue build up and messy animations)
What's the easiest/best way to do this?
$(document).ready(function() {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
$('.slider_container').hover(function() {
//Mouse on
n = 0;
$('.slider').stop(true, false);
}, function() {
//Mouse off
n = 1;
if (fnct == 0) sliderLoop();
});
//Called in Slide Loop
function animateSlider() {
$('.slider').delay(3000).animate({ marginLeft: -(slide_width * i) }, function() {
i++;
sliderLoop();
});
}
var i = 0;
var fnct = 0
//Called in Doc Load
function sliderLoop() {
fnct = 1
if(n == 1) {
if (i < number_of_slides) {
animateSlider();
}
else
{
i = 0;
sliderLoop();
}
}
fnct = 0
}
sliderLoop();
});
The slider works fine normally, but if I quickly move my mouse on and off it, then the slider starts jolting back and forth rapidly...been trying to come up with a solution for this for hours now..
Here's what fixed it, works a charm!
$(document).ready(function() {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,3000);
});
var marginSize = i = 1;
var fnctcmp = 0;
//Called in Doc Load
function sliderLoop() {
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize });
}
t = setInterval(sliderLoop,3000);
});

pausing function on hover

I have a function written in javascript that allows me to scroll through an array of images iterated at a certain interval, now I would like to add some more functionality to it by pausing the rotation when I hover over any of the images in the array.
Javascript
(function() {
var rotator = document.getElementById('bigImage');
var imageDir = '../images/headers/';
var delayInSeconds = 5;
var images = ['ImageOne.png', 'ImageTwo.png', 'ImageThree.png', 'ImageFour.png',
'ImageFive.png',
'ImageSix.png'];
var num = 0;
var changeImage = function() {
var len = images.length;
bigImage.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();​
You could store the id returned from setInterval, and pass it to clearInterval when the image is hovered over.
So, on mouse over, you clear, and on mouse out you set it going again.
Hope that helps!
Use jQuery:
var rotationRunning = true;
var changeImage = function() {
if (rotationRunning) {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len)
num = 0;
}
}
};
$(rotator).hover(
function() { rotationRunning = false; },
function() { rotationRunning = true; }
);

Categories

Resources