Create a copy of a JQuery slider

Hello there, I'm a first time poster but have been reading for a while now. I've been working on creating a simple jQuery Slider and I'm facing an issue... I want to create a slider that utilizes minimal jQuery and can be easily duplicated on the same page to add another slider.

My main challenge right now is getting the second slider to function properly. I tried duplicating the code and tweaking the CSS, but it goes against the principle of D.R.Y (Don't Repeat Yourself).

I am looking to condense the code so that it can serve two unique sliders efficiently. Thanks a lot for any help from the S.O. Community!

Codepen

jQuery(document).ready(function ($) {

      $('#checkbox').change(function(){
        setInterval(function () {
            moveRight();
        }, 3000);
      });
      
    var slideCount = $('#slider ul li').length;
    var slideWidth = $('#slider ul li').width();
    var slideHeight = $('#slider ul li').height();
    var sliderUlWidth = slideCount * slideWidth;

    $('#slider').css({ width: slideWidth, height: slideHeight });

    $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

        $('#slider ul li:last-child').prependTo('#slider ul');

        function moveLeft() {
            $('#slider ul').animate({
                left: + slideWidth
            }, 200, function () {
                $('#slider ul li:last-child').prependTo('#slider ul');
                $('#slider ul').css('left', '');
            });
        };

        function moveRight() {
            $('#slider ul').animate({
                left: - slideWidth
            }, 200, function () {
                $('#slider ul li:first-child').appendTo('#slider ul');
                $('#slider ul').css('left', '');
            });
        };

        $('a.control_prev').click(function () {
            moveLeft();
        });

        $('a.control_next').click(function () {
            moveRight();
        });

    });    
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);

    html {
      border-top: 5px solid #fff;
      background: #58DDAF;
      color: #2a2a2a;
    }

    html, body {
      margin: 0;
      padding: 0;
      font-family: 'Open Sans';
    }

    h1 {
      color: #fff;
      text-align: center;
      font-weight: 300;
    }

    #slider {
      position: relative;
      overflow: hidden;
      margin: 20px auto 0 auto;
      border-radius: 4px;
    }

    #slider ul {
      position: relative;
      margin: 0;
      padding: 0;
      height: 200px;
      list-style: none;
    }

    #slider ul li {
      position: relative;
      display: block;
      float: left;
      margin: 0;
      padding: 0;
      width: 500px;
      height: 300px;
      background: #ccc;
      text-align: center;
      line-height: 300px;
    }

    a.control_prev, a.control_next {
      position: absolute;
      top: 40%;
      z-index: 999;
      display: block;
      padding: 4% 3%;
      width: auto;
      height: auto;
      background: #2a2a2a;
      color: #fff;
      text-decoration: none;
      font-weight: 600;
      font-size: 18px;
      opacity: 0.8;
      cursor: pointer;
    }

    a.control_prev:hover, a.control_next:hover {
      opacity: 1;
      -webkit-transition: all 0.2s ease;
    }

    a.control_prev {
      border-radius: 0 2px 2px 0;
    }

    a.control_next {
      right: 0;
      border-radius: 2px 0 0 2px;
    }

    .slider_option {
      position: relative;
      margin: 10px auto;
      width: 160px;
      font-size: 18px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1>Incredibly Basic Slider</h1>
    <div id="slider">
      <a href="#" class="control_next"> >> </a>
      <a href="#" class="control_prev"> << </a>
      <ul>
        <li>SLIDE 1</li>
        <li style="background: #aaa;">SLIDE 2</li>
        <li>SLIDE 3</li>
        <li style="background: #aaa;">SLIDE 4</li>
      </ul>  
    </div>

    <div class="slider_option">
      <input type="checkbox" id="checkbox">
      <label for="checkbox">Autoplay Slider</label>
    </div>

If you prefer, feel free to use your favorite editor for this task.

Answer №1

Your main problem lies in the fact that you are using the same ID for animating your slider. To resolve this issue, it is important to make the animation specific to the targeted slider only.

Here are the changes I have made:

  1. I removed the ID named 'slider' and replaced it with a class. While you can still use IDs for sliders, ensure they are not duplicated.
  2. In the button click events, I provided a function to animate the slider associated with the parent button. By doing this, the moveLeft/moveRight functions will now only animate the active slider.

It's worth noting that a similar approach needs to be taken for the autoplay function. My recommendation is to place the checkbox within the slider DIV.

jQuery(document).ready(function($) {

  var slideCount = $('.slider ul li').length;
  var slideWidth = $('.slider ul li').width();
  var slideHeight = $('.slider ul li').height();
  var sliderUlWidth = slideCount * slideWidth;

  $('.slider').css({width: slideWidth, height: slideHeight});
  $('.slider ul').css({ width: sliderUlWidth, marginLeft: -slideWidth});
  $('.slider ul li:last-child').prependTo('.slider ul');

  function moveLeft(slider) {
    
    $(slider).find('ul').animate({
        left: +slideWidth
    }, 200, function() {
        var sliderUl = $(slider).find('ul');
        $(slider).find('ul li:last-child').prependTo(sliderUl);
        $(slider).find('ul').css('left', '');
    });
    
  };

  function moveRight(slider) {
    
    $(slider).find('ul').animate({
        left: -slideWidth
    }, 200, function() {
        var sliderUl = $(slider).find('ul');
        $(slider).find('ul li:first-child').appendTo(sliderUl);
        $(slider).find('ul').css('left', '');
    });
    
  };

  $('a.control_prev').click(function() {
      moveLeft($(this).parent());
  });

  $('a.control_next').click(function() {
      moveRight($(this).parent());
  });
  
  $('#checkbox').change(function() {
     setInterval(function() {
         moveRight();
     }, 3000);
  });

});
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);
 html {
  border-top: 5px solid #fff;
  background: #58DDAF;
  color: #2a2a2a;
}
html,
body {
  margin: 0;
  padding: 0;
  font-family: 'Open Sans';
}
h1 {
  color: #fff;
  text-align: center;
  font-weight: 300;
}
.slider {
  position: relative;
  overflow: hidden;
  margin: 20px auto 0 auto;
  border-radius: 4px;
}
.slider ul {
  position: relative;
  margin: 0;
  padding: 0;
  height: 200px;
  list-style: none;
}
.slider ul li {
  position: relative;
  display: block;
  float: left;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 300px;
  background: #ccc;
  text-align: center;
  line-height: 300px;
}
a.control_prev,
a.control_next {
  position: absolute;
  top: 40%;
  z-index: 999;
  display: block;
  padding: 4% 3%;
  width: auto;
  height: auto;
  background: #2a2a2a;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  font-size: 18px;
  opacity: 0.8;
  cursor: pointer;
}
a.control_prev:hover,
a.control_next:hover {
  opacity: 1;
  -webkit-transition: all 0.2s ease;
}
a.control_prev {
  border-radius: 0 2px 2px 0;
}
a.control_next {
  right: 0;
  border-radius: 2px 0 0 2px;
}
.slider_option {
  position: relative;
  margin: 10px auto;
  width: 160px;
  font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
  <a href="#" class="control_next"> >> </a>
  <a href="#" class="control_prev"> << </a>
      <ul>
        <li>SLIDE 1</li>
        <li style="background: #aaa;">SLIDE 2</li>
        <li>SLIDE 3</li>
        <li style="background: #aaa;">SLIDE 4</li>
      </ul>
</div>

<div class="slider">
  <a class="control_next"> >> </a>
  <a class="control_prev"> << </a>
      <ul>
        <li>SLIDE 1</li>
        <li style="background: #aaa;">SLIDE 2</li>
        <li>SLIDE 3</li>
        <li style="background: #aaa;">SLIDE 4</li>
      </ul>
</div>

<div class="slider_option">
  <input type="checkbox" id="checkbox">
  <label for="checkbox">Autoplay Slider</label>
</div>

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

Styling multiple divs using CSS

What is the method for attaching CSS to sp-copyright? <div class="container"> <div class="row"> <div id="sp-footer1" class="col-sm-12 col-md-12"> <div class="sp-column "> <span class="sp-copyright"> ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

does not provide an accurate response

Communication between pages can be achieved by passing email values like this: $.ajax({ type:'post', url:'email.php', data:{email: email}, success:function(msg){ alert(msg); } }); In the followi ...

Using jQuery to smoothly animate scrolling to the top of a

How can I create a "scroll to top" button at the bottom of my page that smoothly scrolls to the top? Despite using an "animate({scrollTop})" script, the scroll animation is not working and it jumps directly to the top. This is the script I am using: $(&a ...

Troubleshooting issues with the 'date' input type feature on mobile devices

When I use the following code: <input type='month' ng-readonly='vm.isReadonly' required min="{{vm.threeMonthsAgo}}" max='{{vm.oneMonthAhead}}'/> I am experiencing some difficulties on mobile devices that do not occur o ...

Tips for incorporating IntersectionObserver into an Angular mat-table to enable lazy loading功能?

I am looking to implement lazy loading of more data as the user scrolls down the table using IntersectionObserver. The container I am using is based on the Bootstrap grid system. However, despite using the code below, the callback function is not being tri ...

What is the best way to align an image to flex-end?

I recently started using React and ran into issues trying to align my image using CSS. Despite trying various methods like justifyContent, justifySelf, and floating right, I couldn't get the image to align on the right side of the screen without resor ...

Deactivate the AJAX button after the specified number of clicks

Imagine I have a model called Post, and it can be associated with up to n Comments (where the number is determined by the backend). Now, let's say I have a view that allows users to add a Comment through an AJAX request. What would be the most effecti ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

Adjust the left margin to be flexible while keeping the right margin fixed at 0 to resolve the spacing

To create a responsive design that adjusts based on screen size, I initially set the content width to 500px with a margin of 0 auto. This meant that for a 700px screen, the content would remain at 500px with left and right margins of 100px each. Similarl ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

How to locate a particular element containing specific text using xpath

I have a unique set of spans to work with: <span> <span>foobar</span> <span>textexampleone</span> </span> Currently, I am attempting to utilize xpath in order to locate the span containing "textexampleone" with ...

Steps to keep the gridlines in the chart from moving

Take a look at the example provided in the following link: Labeling the axis with alphanumeric characters. In this particular instance, the gridlines adjust dynamically based on the coordinate values. How can we modify this so that the chart remains static ...

What distinguishes line-height:1.5 from line-height:150% in CSS?

Does anyone have any information on this? ...

Utilizing Bootstrap's popover feature in conjunction with dynamic content load using jQuery's .on

I am facing an issue with my Yii application that utilizes cgridview and ajax pagination. The common problem encountered is the loss of binding with jQuery after paginating, causing functionalities like popovers to stop working. My current popover functio ...

Assigning a value and specifying the selected attribute for an options tag

Trying to understand the challenge of setting both a value and a selected attribute on an options tag. Each one works independently, but not together. For example: <select> <option *ngFor="let item of items" selected [ngValue]="item"> ...

Aligning a rotated paragraph in the middle of its parent container

Here is my current progress: http://jsfiddle.net/2Zrx7/2/ .events{ height:100px; position: relative; } .tt_username{ position: absolute; top:0px; height: 100%; width: 30px; background: #ccc; text-align: center; } .tt_usern ...

Encountering a StaleElementReferenceException with Python Selenium when trying to loop through Select dropdown

Tasked with creating a selenium test in Python for a webpage without access to the source code, I am facing challenges due to encountering a StaleElementReferenceException randomly while trying to extract dropdown menu options. The website uses D3 and JQue ...