I’m figuring out How I can select the current class by pure js, I building a video slider have multiple videos, query selector works perfectly for one video, adding more videos querySelector selection first element, but the slide dynamically changes the HTML class to the next div.
var slide = 0,
slides = document.querySelectorAll('.cover-background > .video_container'),
numSlides = slides.length;
//Functions!!
currentSlide = function() {
var itemToShow = Math.abs(slide % numSlides);
[].forEach.call(slides, function(el) {
el.classList.remove('current_video')
});
slides[itemToShow].classList.add('current_video');
resetProgress();
resetInterval();
},
next = function() {
slide++;
currentSlide();
},
prev = function() {
slide--;
currentSlide();
},
resetProgress = function() {
var elm = document.querySelector('.progressbar'),
newone = elm.cloneNode(true),
x = elm.parentNode.replaceChild(newone, elm);
},
resetslide = function() {
var elm = document.querySelector('#slides > li'),
newone = elm.cloneNode(true),
x = elm.parentNode.replaceChild(newone, elm);
},
resetInterval = function() {
clearInterval(autonext);
autonext = setInterval(function() {
slide++;
currentSlide();
}, 10000);
},
autonext = setInterval(function() {
next();
}, 10000);
let video = document.querySelectorAll(".current_video > .video");
console.log(video);
video.autoplay = true;
video.load();
<div class="cover-background">
<div id="first" class="video_container current_video" data-key="0">
<video class="video" width="100%" height="auto" autoplay loop muted>
<source src="videos/video_1.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
<div id="second" class="video_container" data-key="0">
<video class="video" width="100%" height="auto" autoplay loop muted>
<source src="videos/video_2.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
<div id="third" class="video_container" data-key="0">
<video class="video" width="100%" height="auto" autoplay loop muted>
<source src="videos/video_3.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
.current_video class dynamically move to next slide. the console log always gets the first one. also tried with querySelectorAll
and getElementsByClassName()
I’m looking a pure javascript solution.
2
Answers
In case you want to progress through your slider after a set interval then you can do that in a much simpler way:
In this snippet I replaced the videos by images and made the
.current_video
class have a red border.Modified the code by adding the
querySelector
inside the function that is called when the current_video class is added. This ensures that the function is called whenever the class is added, providing a simpler and more efficient workaround.Hope it helps!