When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed.

Here is the code responsible for this functionality. It identifies the current sibling with the active class and then adds it to the previous or next sibling accordingly.

//Slider Directional Controls
$('.buttons .prev').on('click', function() {
    if( position > 0 ) { 
        position--;
        $('.program-slider .slides').css({'right': position * programSliderWidth }); // -- CHANGE 3 --
        $('.navigation .controls').find('li.active').removeClass('active').prev('li').addClass('active');

    }
});

$('.buttons .next').on('click', function() {
    if( position < totalSlides - 1 ) { 
         position++;
          $('.program-slider .slides').css({'right': position * programSliderWidth});   
          $('.navigation .controls').find('li.active').removeClass('active').next('li').addClass('active');

      }
});

If I want to reset this functionality, where do I begin? My approach involves removing the active class from the current sibling and adding it to the first sibling to indicate that it is the initial slide being displayed.

This is the code snippet I have created for resetting the functionality, yet encountering issues when clicking on directional controls of the slider as it fails to pass the active class to the subsequent sibling. To reset, I utilize

$(window).on('resize', function(){})

//Add Class active on Start
$('.navigation .controls li.active').removeClass('active');
$('.navigation .controls li:first-child').addClass('active');

function slider() {

    $('.navigation .controls li.active').removeClass('active');
$('.navigation .controls li:first-child').addClass('active');

    var programSliderWidth = $('.program-slider').width(),
        sliderContainer    = $('.program-slider .slides'),
        slides             = $('.program-slider .slides li'),
        move               = 0,
        position           = 0,
        totalSlides        = $('.program-slider .slides li').length;  


    //Apply width based on the width of the .program-slider
    slides.width(programSliderWidth);

    //Apply Maximum width based on number of slides
    sliderContainer.width(totalSlides * programSliderWidth);

    //Slider Controls
    $('.navigation .controls li').on('click', function() {
        position = $(this).index(); // -- CHANGE 1 --
        var move     = position*programSliderWidth;

        $('.program-slider .slides').css({'right': move});

        $('.navigation .controls li.active').removeClass('active');
        $(this).addClass('active');
    
    });

    //Slider Directional Controls
    $('.buttons .prev').on('click', function() {
        if( position > 0 ) { 
            position--;
            $('.program-slider .slides').css({'right': position * programSliderWidth }); // -- CHANGE 3 --
            $('.navigation .controls').find('li.active').removeClass('active').prev('li').addClass('active');

        }
    });

    $('.buttons .next').on('click', function() {
        if( position < totalSlides - 1 ) { 
             position++;
              $('.program-slider .slides').css({'right': position * programSliderWidth});   
              $('.navigation .controls').find('li.active').removeClass('active').next('li').addClass('active');

          }
    });
}


$(document).ready(function() {
    slider();
});

$(window).on('resize', function() {
    slider();
})
/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline; }

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block; }

body {
  line-height: 1; }

ol, ul {
  list-style: none; }

blockquote, q {
  quotes: none; }

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none; }

table {
  border-collapse: collapse;
  border-spacing: 0; }

* {
  box-sizing: border-box; }

.program-slider {
  max-width: 1280px;
  margin: 0 auto;
  height: 200px;
  background-color: beige;
  overflow: hidden; }
  .program-slider .slides {
    overflow: hidden;
    position: relative;
    right: 0;
    -webkit-transition: all 0.3s linear; }
    .program-slider .slides li {
      position: relative;
      float: left;
      -webkit-transition: all 0.3s linear; }

.navigation {
  max-width: 1280px;
  margin: 0 auto; }
  .navigation .controls li {
    display: inline-block;
    padding: 10px;
    width: 25%;
    float: left; }
    .navigation .controls li.active {
      background-color: teal;
      color: #fff; }

.buttons {
  position: absolute;
  top: 30%; }

/*# sourceMappingURL=style.css.map */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="program-slider">
   <ul class="slides">
       <li>Slide 1</li>
       <li>Slide 2</li>
       <li>Slide 3</li>
       <li>Slide 4</li>
   </ul>


<div class="buttons">
    <ul>
        <li class="prev">Prev</li>
        <li class="next">Next</li>
    </ul>
</div>


</div>

<div class="navigation">
    <ul class="controls">
        <li>slide 1</li>
        <li>slide 2</li>
        <li>slide 3</li>
        <li>slide 4</li>
    </ul>
</div>

Answer №1

Let's enhance your code by using the :eq selector in CSS to work with the li index instead of using .prev('li') and .next('li').

Below is an explanation of how your code can be structured:

function slider() {
    $('.navigation .controls li.active').removeClass('active');
    $('.navigation .controls li:first-child').addClass('active');

    var programSliderWidth = $('.program-slider').width(),
        sliderContainer = $('.program-slider .slides'),
        slides = $('.program-slider .slides li'),
        move = 0,
        position = 0,
        totalSlides = $('.program-slider .slides li').length;  

    // Set slide widths based on program-slider width
    slides.width(programSliderWidth);

    // Set maximum width based on number of slides
    sliderContainer.width(totalSlides * programSliderWidth);

    // Slider Controls
    $('.navigation .controls li').on('click', function() {
        position = $(this).index();
        var move = position * programSliderWidth;

        $('.program-slider .slides').css({'right': move});

        $('.navigation .controls li.active').removeClass('active');
        $(this).addClass('active');
    });

    // Slider Directional Controls
    $('.buttons .prev').on('click', function() {
        position = (position > 0) ? position - 1 : totalSlides - 1;
        $('.program-slider .slides').css({'right': position * programSliderWidth});
        $('.navigation .controls li').removeClass('active');
        $('.navigation .controls li:eq(' + position + ')').addClass('active');
    });

    $('.buttons .next').on('click', function() {
        position = (position < totalSlides - 1) ? position + 1 : 0;  
        $('.program-slider .slides').css({'right': position * programSliderWidth});
        $('.navigation .controls li').removeClass('active');
        $('.navigation .controls li:eq(' + position + ')').addClass('active');
    });
}

$(document).ready(function() {
    slider();
});

$(window).on('resize', function() {
    slider();
})
// CSS Styling and Reset Code

// JavaScript Libraries
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

// HTML Structure for Slider
<div class="program-slider">
   <ul class="slides">
       <li>Slide 1</li>
       <li>Slide 2</li>
       <li>Slide 3</li>
       <li>Slide 4</li>
   </ul>

// Navigation Buttons
<div class="buttons">
    <ul>
        <li class="prev">Prev</li>
        <li class="next">Next</li>
    </ul>
</div>

// Navigation Controls
<div class="navigation">
    <ul class="controls">
        <li>slide 1</li>
        <li>slide 2</li>
        <li>slide 3</li>
        <li>slide 4</li>
    </ul>
</div>

Explanation:

The code has been improved by utilizing the :eq selector in CSS to control the li index, making it easier to handle the position value within the code. The logic for controlling the position variable has been simplified by incorporating conditional statements for the previous and next events. Additionally, classes are added or removed dynamically based on the position value using CSS selectors.

This approach enhances the functionality and readability of the code. Make sure to refer to this explanation for a better understanding of the code structure.

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

AngularJS: when only one line is visible, the other remains hidden

Issue with AngularJS: Only One Line Displaying Instead of Both I am encountering an issue with my AngularJS code where only one of the elements is displaying on my page. function Today($scope, $timeout) { $scope.now_time = 0; (function update() { ...

Seamless animated loading gif as a looping background visual

Is there a way to find a GIF that can be used as a repeated background on an HTML element, creating the illusion of a seamless block? https://i.sstatic.net/5BKxW.gif (source: opengraphicdesign.com) I am looking for an 80x80 GIF that can be repeated as ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

How about this: "Can you turn a picture into text with just one click?"

Seeking assistance to enhance the 'About Us' page on our website. Each team member has a profile with their email address listed below, but we want to add a picture that disappears when clicked, revealing the email address in its place. You can ...

The Vue computed property is failing to retrieve the data it needs

I'm having trouble with the computed() property not retrieving data. Data was initialized in the created() property. Am I missing something here? Any guidance on how to resolve this issue would be greatly appreciated. const randomPlayers = { temp ...

What causes identical request headers to result in receiving different Ajax content?

Whenever I access the website for a journal called Applied Physics Letters at "", I notice that there are multiple AJAX fields on the page. Each time I click "show abstract", the abstract for the corresponding article is displayed. By using "inspect elemen ...

Transformations in Object Attributes Following an AJAX Submission

For my latest project, I am developing an application using node.js and express. One of the functionalities involves making a POST request that sends an array of strings to the server. However, upon inspecting the request body on the server side, I noticed ...

What makes this lambda function in TypeScript successfully execute without any errors?

I was under the impression that this code let x: (a: { b: number }) => void = (a: { b: number, c: string }) => { alert(a.c) }; x({ b: 123 }); would result in an error because the lambda function requires an additional property on the a argument, m ...

Effortlessly switch between CSS animation styles while adjusting animation settings

My HTML element with animation is defined as follows: <div id="box"></div> The box starts by moving 200 pixels to the right, taking 4 seconds to complete. .anim { animation-name: anim; animation-duration: 4s; animation-t ...

How to extract a one-of-a-kind identification number from the browser using just JavaScript in a basic HTML file?

Is there a way to obtain a distinct identification number from a browser without resorting to techniques such as generating and storing a unique number in cookies or local storage, and without utilizing a server-side language? ...

Explore the full range of events available on the Angular UI-Calendar, the innovative directive designed for Arshaw FullCalendar

Utilizing external events with Angular ui-calendar: HTML: <div id='external-events'> <ul> <li class='fc-event'>Event 1</li> <li class='fc-event'>Event 2< ...

Issue with File Input not being validated by Bootstrap Validator

Looking for help with a form field that should only accept .jpg or .png images of a certain file size. The validation doesn't seem to be working when tested with invalid file types. What am I missing? It should function like the example shown here. C ...

Main content with a floating aside menu

I am currently using the CoreUI admin template. The layout I have set up is the basic one outlined on the following page: My goal is to make the aside menu appear on the right side of the main content, floating over it rather than inline and reducing the ...

Navigating Angular on Internet ExplorerUnderstanding Angular's Compatibility

Having some trouble with an Angular app I'm developing. It displays perfectly on Chrome, but not at all on IE. Any tips on how to configure IE to show it correctly, or should I make changes to the app to ensure compatibility with IE? You can see how i ...

Connecting a CSS file with an HTML document

Having an issue with my CSS. For instance, here is a snippet from my CSS file .readmore { font-style: italic; text-decoration: none; color: #509743; padding-left: 15px; background: url(../images/more.png) no-repeat 0 50%; } .readmore: ...

Are the menubar menus positioned beneath a different div element?

Currently facing an issue with an HTML Menubar where the menus are appearing below another div, and not getting displayed as expected: ...

Loading jsp content into a div dynamically within the same jsp file upon clicking a link

Currently, I am working on creating a user account page. On this page, my goal is to display related JSP pages in a div on the right side when clicking links like 'search user' or 'prepare notes' on the left side. In my initial attempt ...