简体   繁体   中英

Javascript slider with arrows

I want to make a slider with arrows i tried several methods but i failed still new so i dont really know where to begin here is my html,

    <div class="previous-butn"></div>
<div class="slider">
<a href="">
<img src="assets/media/images/colormood-slide.jpg" alt="">
</a>
<div class="next-butn"></div>

and here is my js

const currentSlide = document.querySelector('.slider img');
const projectSlide = [
'assets/media/images/colormood-slide.jpg',
'assets/media/images/cancellato-slide.jpg',
'assets/media/images/grazia-slide.jpg',
'assets/media/images/maxnextdoor-slide.jpg',
'assets/media/images/sasha-slide.jpg',
'assets/media/images/windinthecity-slide.jpg',
'assets/media/images/gullsnitt-slide.jpg'
];
let slidesCounter = 1;

First of all create the HTML and CSS for your slider. Use one single div that contains everything else. In your slider case, the container div should contain two major divs, one for the slider images and another containing control buttons, that is, the arrows.

In the container of slider images, put multiple images.

Use CSS a class such as 'active' on the first image only. Now write CSS to hide all images except the one having the 'active' class. Also use CSS to place the navigator arrows where you want them to be.

Now open the page in the browser and see if it is okay. When its okay move forward to JS

Add click events to your arrow buttons (not considering autoplay at this moment)

Following is the logic for NEXT button

  1. CurrentActiveImageIndex = Get the index of the image with the class active
  2. TotalNumberOfImages = Count total number of images in the slider
  3. NextActiveImageIndex = CurrentActiveImageIndex + 1
  4. IF NextActiveImageIndex == TotalNumberOfImages
  5. THEN NextActiveImageIndex = 0
  6. Remove the class active from all images
  7. Add the class active to the image at NextActiveImageIndex

Logic for the PREVIOUS button would just the opposite, following are the changed lines only

  1. NextActiveImageIndex = CurrentActiveImageIndex - 1
  2. IF NextActiveImageIndex < 0
  3. THEN NextActiveImageIndex = TotalNumberOfImages - 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM