Could you explain this simple image slider code line by line? - javascript

Are you able explain this simple image slider code line by line?
I'm particularly interested in where the n and no values come from in currentSlide(no) + plusSlides(n).
var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");
var interval;
var pauseButton = document.getElementById("pause");
showSlides();
playSlideshow();
function showSlides() {
var i;
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].style.display = "block";
}
// Manual control
function currentSlide(no) {
var i;
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex = no;
slides[no - 1].style.display = "block";
}
function plusSlides(n) {
var newslideIndex = slideIndex + n;
if (newslideIndex < 6 && newslideIndex > 0) {
currentSlide(newslideIndex);
}
}
Edited to add rest of the code.
// Pause
var playing = true;
function pauseSlideshow() {
var pauseButton = document.getElementById("pause");
pauseButton.innerHTML = "▸";
playing = false;
clearInterval(interval);
}
function playSlideshow() {
pauseButton.innerHTML = "⏸";
playing = true;
interval = setInterval(showSlides, 5000);
}
pauseButton.onclick = function () {
if (playing) {
pauseSlideshow();
} else {
playSlideshow();
}
};
As per the comments, I have added additional code.

Yes, can do!
The first function showSlides is called. It first makes every element with the mySlides class invisible (basically hides all your slides). Then it increments the slide index and checks to see if the index is over the total amount of slides so it can start from the beginning again. Finally it shows the slide that the index is referring to.
The currentSlide function sets the active slide to the index provided in the no argument. First it hides all the slides and then sets the new slide index to what no is and then shows that slide.
Finally plusSlides goes forward (or backwards if using a negative number) n slides. The if statement checks if the index is between 1 and 5. If it is the slide that corresponds with the new index is shown.
A few notes
for loops can be written without a variable declaration preceding it like this
for(let x = 0; x < 100; x++){
console.log(x);
}
In your plusSides function, you check for a specific range, but you could base it off of the amount of slides with slides.length like in showSlides. Also, I would recommend making sure that if the index does happen to fall out of this range to set the index to a default value.
if (newslideIndex < slides.length && newslideIndex > 0) {
currentSlide(newslideIndex);
} else {
currentSlide(1);
}
That is all!

Related

Overlapped slide still getting clicked

The slide that I turned the opacity to 0 on is still clickable even though I set pointer events to none. Basically I have 2 slides on this slideshow and even if i'm on the first slide when I click on it, it goes to the 2nd slides hyperlink. Image This image shows the code is changing the pointer event and also the opacity correctly but for some reason when I click on the first slide on the website it still sends me to the second slides hyperlink.
//programming slideshow
$(function () {
var slide_index = 1;
displaySlides(slide_index);
function nextSlide() {
displaySlides(slide_index++);
}
function prevslide() {
displaySlides(slide_index--);
}
function displaySlides() {
var i;
var slides = document.getElementsByClassName("programming-slides");
if (slide_index > slides.length) { slide_index = 1 }
if (slide_index < 1) { slide_index = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.opacity = 0;
}
slides[slide_index - 1].style.opacity = 1;
for (var i = 0; i < slides.length; i++) {
// If the slide is not visible, set its pointer-events to none
if (slides[i].style.opacity === '0') {
slides[i].style.pointerEvents = 'none';
} else {
// Otherwise, set its pointer-events to auto
slides[i].style.pointerEvents = 'auto';
}
}
}
var next = document.getElementById('programming-next');
next.addEventListener('click', nextSlide);
var prev = document.getElementById('programming-prev');
prev.addEventListener('click', prevslide);
})
Started to fix it by adding in z index to the code in the slides js and also to some other css elements that fixed the overlapping problem and now all the features are working
for (var i = 0; i < slides.length; i++) {
// If the slide is not visible, set its pointer-events to none
if (slides[i].style.opacity === '0') {
slides[i].style.pointerEvents = 'none';
slides[i].style.zIndex = 0;
} else {
// Otherwise, set its pointer-events to auto
slides[i].style.pointerEvents = 'auto';
slides[i].style.zIndex = 1;
}

Javascript function is working, but when I click the second time it doesn't work anymore

I have a slider on my website page, and I wanted to create a link that redirects to a specific slide of the slider, that contains 3 slides. Because I'm a beginner in javascript, I tried the easiest way that I could think, which is to click a certain number of times according to the current slide, so for example, if my current slide position is equal to 2[0,1,2], and I want to go to position 1, I can press the next button 2 times using a Javascript click() event. It's working like a charm, but when I click for the second time, it doesn't work. I would like to know why this is happening.
const mySlide = document.querySelectorAll('.mySlides');
let counter = 1;
slidefun(counter);
let timer = setInterval(autoSlide, 8100);
function autoSlide() {
counter += 1;
slidefun(counter);
}
function plusSlides(n) {
counter += n;
slidefun(counter);
resetTimer();
}
function currentSlide(n) {
counter = n;
slidefun(counter);
resetTimer();
}
function resetTimer() {
clearInterval(timer);
timer = setInterval(autoSlide, 8100);
}
function slidefun(n) {
let i;
for(i = 0;i<mySlide.length;i++){
mySlide[i].style.display = "none";
}
if(n > mySlide.length){
counter = 1;
}
if(n < 1){
counter = mySlide.length;
}
mySlide[counter - 1].style.display = "block";
}
const slide2 = document.getElementById('slide2');
var slideButton = document.getElementById('myButton');
slideButton.addEventListener('click', openSlide);
nextButton = document.getElementsByClassName('next');
nextButton.addEventListener('click', slideSelected);
function slideSelected(){
if(currentSlide == currentSlide(0)){
nextButton.click()
}else if(currentSlide == currentSlide(2)){
nextButton.click();
nextButton.click();
}
}

Autoplaying javascript slideshow that has multiple slideshows on one page not working

I'm trying to make a simple javascript slideshow, that will use prev and next buttons to cycle through, and autoplay. Plus, require to have multiple slideshows on one page.
Can't get the autoplay on load to work? Am I missing something?
The code I've been using works with multiple on one page, and prev and next buttons work. However the auto play doesn't work on the window load, but does start to work when you click one of the previous and next buttons.
Thanks.
var slideIndex = [1,1,1,1,1]
var slideId = ["mySlides1", "mySlides2", "mySlides3", "mySlides4", "mySlides5"]
showSlides(1, 0);
showSlides(1, 1);
showSlides(1, 2);
showSlides(1, 3);
showSlides(1, 4);
var myTimer;
window.addEventListener("load",function() {
showSlides(slideIndex[no], no);
myTimer = setInterval(function(){plusSlides(1, no)}, 4000);
})
function plusSlides(n, no){
clearInterval(myTimer);
if (n < 0){
showSlides(slideIndex[no] -= 1, no);
} else {
showSlides(slideIndex[no] += 1, no);
}
if (n === -1){
myTimer = setInterval(function(){plusSlides(n + 2, no)}, 4000);
} else {
myTimer = setInterval(function(){plusSlides(n + 1, no)}, 4000);
}
}
function currentSlide(n, no){
clearInterval(myTimer);
myTimer = setInterval(function(){plusSlides(n + 1, no)}, 4000);
showSlides(slideIndex[no] = n, no);
}
function showSlides(n, no){
var i;
var slides = document.getElementsByClassName(slideId[no]);
var dotname = "dot" + no;
var dots = document.getElementsByName(dotname);
if (n > slides.length) {slideIndex[no] = 1}
if (n < 1) {slideIndex[no] = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active_slide", "");
}
slides[slideIndex[no]-1].style.display = "block";
dots[slideIndex[no]-1].className += " active_slide";
}
I suggest you don't reset your interval.
If you have an array like so:
const slides = [
'slideOne', 'slideTwo',
'slideThree', 'slideFour',
'slideFive', 'slideSix'
];
you can just do:
let autoSliderInterval;
let currentSlideIndex = 0;
function _autoSlide() {
// Increase Slide index
currentSlideIndex++;
// If slides are at the end begin from the start
if(currentSlideIndex >= slides.length) currentSlideIndex = 0;
// Display current slide
displaySlide(currentSlideIndex);
}
Then if you want to acutoscroll just set the timeout:
autoSliderInterval = setInterval(_autoSlide, <your time>);
And if you want to stop auto sliding (for example this could happen when the user clicks on one button) just do:
clearInterval(autoSliderInterval).
Basic example:
const display = document.getElementById('display');
const button_sliderPrevious = document.getElementById('button_sliderPrevious');
const button_sliderNext = document.getElementById('button_sliderNext');
button_sliderPrevious.addEventListener('click', () => shiftSlide(-1));
button_sliderNext.addEventListener('click', () => shiftSlide(1));
const slides = [
'slideOne', 'slideTwo',
'slideThree', 'slideFour',
'slideFive', 'slideSix'
];
let autoSliderInterval = setInterval(_autoSlide, 500);
let currentSlideIndex = 0;
function shiftSlide(amount) {
// Stop the inverval
if(autoSliderInterval !== null) {
clearInterval(autoSliderInterval);
autoSliderInterval = null;
}
// Shift the slide index
currentSlideIndex += amount;
// Check if below zero (if yes set to max)
if(currentSlideIndex < 0) currentSlideIndex = slides.length - 1;
// Check if over max (set to zero)
if(currentSlideIndex >= slides.length) currentSlideIndex = 0;
// Display the slide
displaySlide(currentSlideIndex);
}
function _autoSlide() {
// Increase Slide index
currentSlideIndex++;
// If slides are at the end begin from the start
if(currentSlideIndex >= slides.length) currentSlideIndex = 0;
// Display current slide
displaySlide(currentSlideIndex);
}
function displaySlide(slideIndex) {
display.innerText = slides[slideIndex];
}
#display {
text-align: center;
height: 50px;
width: 100%;
border: 1px solid lightgray;
}
<div id="display"></div>
<button id="button_sliderPrevious">Previous</button>
<button id="button_sliderNext">Next</button>
Try this one.
i hope it will work for you.
<script type="text/javascript">
var slideIndex = [1,1];
var slideId = ["mySlides1", "mySlides2"]
showSlides(1, 0);
showSlides(1, 1);
function plusSlides(n, no) {
showSlides(slideIndex[no] += n, no);
}
function showSlides(n, no) {
var i;
var x = document.getElementsByClassName(slideId[no]);
if (n > x.length) {slideIndex[no] = 1}
if (n < 1) {slideIndex[no] = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex[no]-1].style.display = "block";
}
setInterval(function(){
$(".next.slide_buttons").click();
},3000);
</script>

Dont figure what s the role of the counter in javascript

I want to create a fullscreen image slider in js so I watched a tutorial and I understand most of it beside the 'counter'.I know that its representing the current image but I don't know how it doing that, how is assigned.
HERE IS THE CODE
let sliderImages = document.querySelectorAll(".slide"),
arrowLeft = document.querySelector("#arrow-left"),
arrowRight = document.querySelector("#arrow-right"),
current = 0; (!!!!THIS ONE I DON`T UNDERSTAND HOW IT S REPRESENTING THE CURRENT IMAGE!!!
// Clear all images
function reset() {
for (let i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = "none";
}
}
// Init slider
function startSlide() {
reset();
sliderImages[0].style.display = "block";
}
// Show prev
function slideLeft() {
reset();
sliderImages[current - 1].style.display = "block";
current--;
}
// Left arrow click
arrowLeft.addEventListener("click", function () {
if (current === 0) {
current = sliderImages.length;
}
slideLeft();
});
// Show next
function slideRight() {
reset();
sliderImages[current + 1].style.display = "block";
current++;
}
// Right arrow click
arrowRight.addEventListener("click", function () {
if (current === sliderImages.length - 1) {
current = -1;
}
slideRight();
});
startSlide();
!! HERE IS THE LINK FROM TUTORIAL https://youtu.be/7ZO2RTMNSAY
Current is being used for the index of the array that contains all the elements with the class name of slide.
It might be beneficial for you to read more about arrays: https://www.w3schools.com/js/js_arrays.asp

Why are some elements undefined in my slider script?

I am creating an image slider for JavaScript. I have it so that my left and right arrows display the next image. I was thinking to add a setInterval method to just change the display image every few seconds. I was assuming it would be as easy as calling the function to click the right image every 3 seconds. But I get an error saying
index.js:26 Uncaught TypeError: Cannot read property 'style' of undefined
at slideRight (index.js:26)
Heres my code
let sliderImages = document.querySelectorAll('.slide');
let arrowLeft = document.getElementById('arrow-left');
let arrowRight = document.getElementById('arrow-right');
let current = 0;
function reset() {
for(let i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = 'none';
}
}
function startSlider() {
reset();
sliderImages[0].style.display = 'block';
}
function slideLeft() {
reset();
sliderImages[current - 1].style.display = 'block';
current --;
}
function slideRight() {
reset();
sliderImages[current + 1].style.display = 'block';
console.log(current);
current ++;
console.log(current);
}
arrowLeft.addEventListener('click', function() {
reset()
if(current == 0) {
current = sliderImages.length;
}
slideLeft();
});
arrowRight.addEventListener('click', function () {
if(current == sliderImages.length -1 ) {
current = -1;
}
slideRight();
})
startSlider();
setInterval(slideRight, 3000);
Your problem seems to me to be that when you go too far right that index no longer exists in the array, so you need to use the modulus operator when going right:
sliderImages[(current + 1) % sliderImages.length].style.display = 'block';
And you need to wrap around to the right side when going left too far:
sliderImages[current - 1 >= 0 ?
current - 1 : sliderImages.length - 1].style.display = 'block';
The problem is in sliderImages[current + 1].
When you reach the lastest image current + 1 is an out of bound index and the cooresponding entry in sliderImages returns null.
You probably need to check something like
if (current < sliderImages.length) {
sliderImages[current + 1].style.display = 'block';
current++;
}

Categories

Resources