What is the best way to incorporate next and previous buttons into a jQuery slider using JavaScript?

I recently watched a tutorial on YouTube about creating a slider using jQuery (check it out here).

The tutorial didn't include Previous and Next Buttons.

I'm curious how to add Previous and Next Buttons to the Jquery Slider.

Below is the code snippet that was shared:

'use strict';

$(function() {

    //slider settings
    var width = 720;
    var animationSpeed = 1000;
    var pause = 3000;
    var currentSlide = 1;

    //cache DOM elements
    var $slider = $('#slider');
    var $slideContainer = $('.slides', $slider);
    var $slides = $('.slide', $slider);

    var interval;

    function startSlider() {
        interval = setInterval(function() {
            $slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
                if (++currentSlide === $slides.length) {
                    currentSlide = 1;
                    $slideContainer.css('margin-left', 0);
                }
            });
        }, pause);
    }
    function pauseSlider() {
        clearInterval(interval);
    }

    $slideContainer
        .on('mouseenter', pauseSlider)
        .on('mouseleave', startSlider);

    startSlider();


});
#slider {
    width: 720px;
    height: 400px;
    overflow: hidden;
}

#slider .slides {
    display: block;
    width: 6000px;
    height: 400px;
    margin: 0;
    padding: 0;
}

#slider .slide {
    float: left;
    list-style-type: none;
    width: 720px;
    height: 400px;
}

/* additional css for slides */
.slide1 {background: red;}
.slide2 {background: blue;}
.slide3 {background: green;}
.slide4 {background: purple;}
.slide5 {background: pink;}
<div class="container">
            <div class="header">
                <h1 class="text-muted">jQuery Basic Slider</h1>
            </div>

            <div id="slider">
                <ul class="slides">
                    <li class="slide slide1">slide1</li>
                    <li class="slide slide2">slide2</li>
                    <li class="slide slide3">slide3</li>
                    <li class="slide slide4">slide4</li>
                    <li class="slide slide5">slide5</li>
                    <li class="slide slide1">slide1</li>
                </ul>
            </div>

        </div>

Thank you

Thank you

Answer №1

Check out this solution with detailed comments explaining each step!

$(function() {

  //set up slider configurations
  var width = 720;
  var animationSpeed = 1000;
  var pause = 3000;
  var currentSlide = 1;
  var margin = 0; //Variable to store the margin value

  //cache DOM elements
  var $slider = $('#slider');
  var $slideContainer = $('.slides', $slider);
  var $slides = $('.slide', $slider);
  var length = $slides.length;

  var interval;

  //Create a reusable function for the slider animation
  function Slider() {
    $slideContainer.animate({
      'margin-left': margin //Use variable for margin to access it in multiple functions
    }, animationSpeed, function() {
       console.log(currentSlide) //Log the current slide number
      if (currentSlide === length) { 
        currentSlide = 1;
        margin = 0;
        $slideContainer.css('margin-left', 0); //Reset margin and slide position at end
      }
    });
  }

  function contSlider() {
    interval = setInterval(function() {
      margin -= width; //Adjust margin based on width
      currentSlide++; 
      Slider();
    }, pause);
  }

  function pauseSlider() {
    clearInterval(interval); //Stop the slider animation
  }
  
  function three() {
    clearInterval(interval); //Stop the original slider
    Slider(); //Instantly perform the slider function
    contSlider(); //Resume slider function
  }

  function prevSlider() {
    if (currentSlide > 1) {
      currentSlide--; //Move to previous slide
    } else {
      margin = -width * (length - 1); //Set margin to last slide position
      $slideContainer.css('margin-left', margin); //Jump to last slide instantly
      currentSlide = (length - 1) 
    }
    
    margin += width; //Adjust margin for previous slide
    three(); 
  }

  function nextSlider() {
    if (currentSlide < length){
    margin -= width; //Move to next slide
    currentSlide++; 
    }
    three(); 
  }

  $slideContainer
    .on('mouseenter', pauseSlider)
    .on('mouseleave', contSlider);

  $(".prev-slide").on("click", prevSlider); //Bind button click event to previous slide action
  $(".next-slide").on("click", nextSlider); //

  contSlider(); //Start the initial slider animation

});
.button {  display: none  }

#slider:hover .button {
  display: block;
  font-size: 3em;
  font-weight: bold;
  color: #fff;
  position: absolute;
  top: 180px;
  cursor: pointer;
}

.prev-slide {
  left: 10px;
}

.next-slide {
  right: 10px;
}

#slider {
  width: 720px;
  height: 400px;
  overflow: hidden;
  position: relative;
}

#slider .slides {
  display: block;
  width: 6000px;
  height: 400px;
  margin: 0;
  padding: 0;
}

#slider .slide {
  float: left;
  list-style-type: none;
  width: 720px;
  height: 400px;
}


/* helper css, since we don't have images */

.slide1 {
  background: red;
}

.slide2 {
  background: blue;
}

.slide3 {
  background: green;
}

.slide4 {
  background: purple;
}

.slide5 {
  background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    <h1 class="text-muted">jQuery Basic Slider</h1>
  </div>
  <div id="slider">
    <div class="prev-slide button">&lt;</div>
    <div class="next-slide button">&gt;</div>
    <ul class="slides">
      <li class="slide slide1">slide1</li>
      <li class="slide slide2">slide2</li>
      <li class="slide slide3">slide3</li>
      <li class="slide slide4">slide4</li>
      <li class="slide slide5">slide5</li>
      <li class="slide slide1">slide1</li>
    </ul>
  </div>

</div>

Answer №2

By implementing a click function for next and prev, you can adjust the margin-left property accordingly:

$('#next').click(function(){
      pauseSlider();
      $slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
        console.log(width);
        if (++currentSlide === $slides.length) {
          currentSlide = 1;
          $slideContainer.css('margin-left', 0);
        }
      });
     startSlider();
  });

  $('#prev').click(function(){
      console.log(currentSlide);
              console.log($slides.length);
      pauseSlider();
      $slideContainer.animate({'margin-left': '+='+width}, animationSpeed, function() {
        if (--currentSlide === 1) {
          currentSlide = 6;
          $slideContainer.css('margin-left', -(width * 5));
          console.log('first');
        }
      });
     startSlider();
  });

For testing purposes, check out the codepen I've created: http://codepen.io/adrianrios/pen/evLOyQ

I trust that this information will be beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic slideshow using Jquery Ajax requests

I am looking for help with creating a slideshow using Ajax calls. I have successfully implemented it by adjusting the margin left, but now I need to approach it differently. I have a PHP array that I fetched from a database and I want to use it to display ...

Dealing with multiple ajax requests while utilizing a single fail callback

Looking for a solution: I have two arrays containing deferreds. In order to detect failures in the outer or inner 'when' statements, I currently need to use double 'fail' callbacks. Is there a way to consolidate errors from the inner &a ...

Retrieve text from the input field after a brief pause following each keystroke for uninterrupted typing

I am currently facing an issue with a form that is submitted remotely whenever the elements change. Specifically, when a user types in the search field and hits a key, the form gets submitted multiple times even though only the final submission matters. I ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

Struggling to refresh page due to several getJson requests

I have a HTML page where I am showcasing data from 3 different websites using WordPress API in 3 separate sections of the HTML. Below is my script code: <script> $(document).ready(function(){ $.getJSON("https://thebigscope.com/wp-jso ...

How can we link identical pages to distinct sets of data in the backend and ensure they operate effectively with their respective data?

I'm working on a project where I have a dynamic table on the front-end that gets its data from a MySQL database connected using PHP. Each row in the table has action buttons, with only a delete option for now. The styling is pretty basic as shown belo ...

Divide the <ul> element into two columns with CSS only if the number of <li> items is more than 5

Is it feasible to divide a list into two columns using pure CSS if there are more than 5 child <li> elements? In the scenario I have in mind, this is the desired outcome: <li>1</li> <li>2</li> <li>3</li> ...

Using the jQuery Ternary Operator in Decision Statements

Can someone guide me on writing this code using a ternary operator in the most concise way possible? const isValuePresent = (jQuery('#product-options-wrapper select').val() || jQuery('#product-options-wrapper input').val()) ? true : fa ...

Error: Dom exception 22 - A storage limit was exceeded while trying to add an item

Encountering an issue when using LocalStorage on iPhone with iOS 7. Despite searching for a solution, nothing seems to apply since I am not browsing privately. The default disablement of localStorage in iOS 7 is puzzling. Testing on various websites yield ...

Converting React Router Function into Typescript: A Step-by-Step Guide

Working on a React project that utilizes react-router-dom and the client requires converting the code to TypeScript. I created 2 folders: "RouteWrapper.js" and "ProviderRoutes.js" 1- "RouteWrapper.js" import React from 'react'; import PropTypes ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

What is the process for integrating custom commands in Cypress?

I have successfully implemented custom commands in Cypress and I am using Visual Studio Code as my editor. To enable IntelliSense to recognize these custom commands, I referred to this link. In order to achieve this, I created a cypress/index.d.ts file: ...

`Regular expression for allowing only hyphens and numbers`

I am currently using the RegEx pattern ^[0-9]+$" to only allow digits, but I also want to include hyphens - and spaces as valid characters. Can anyone provide assistance in modifying the RegEx pattern accordingly? Previously, I attempted to achieve this ...

Tips for making a horizontal scrolling container that doesn't hide elements with overflow-y?

I'm struggling to find an example of horizontal scrolling that doesn't hide content with overflow-y. Is there a way to create a horizontally scrolling div where absolutely positioned elements (dropdowns) remain visible? If you have a working ex ...

Trouble installing NPM packages from Artifactory on Windows 10

Problem Description: I am utilizing Artifactory for my NPM packages. When attempting to install them on "Windows - 7", everything is functioning correctly. However, on "Windows - 10" an error is being displayed and the packages are not installing. Error M ...

Error: Attempting to access 'map' property on an undefined object in a ReactJS application

import React, { useEffect, useState } from 'react'; import axios from "axios"; import './List.css'; import { toast } from "react-toastify"; const ListComponent = () => { const url = "http://localhost:4500& ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Performing a repeated action to choose each item from a dropdown menu

I attempted to streamline the process by creating id tags for each dropdown and implementing a loop to select each manufacturer without having to write an extensive amount of code. However, I encountered difficulties and was unable to find a solution. The ...

navigate a specific web address using Express routing

Is there a specific regex pattern that should be used in an Express application to match a URL? For example, if the endpoint is www.mydomain.com/v1/https://www.url-to-be-matched.com. I am aiming to accept https://www.url-to-be-matched.com as parameters. H ...