Attempting to identify the currently active slide within a basic slider

I have created a simple full-page slider using a list and keeping the second list item within the viewport. I am now trying to add an "active" class to the current slide, which is always the second one. I attempted to target it using nth-child(2) but haven't been successful so far due to clutter in my approach.

Is there an easier solution that I might be overlooking?

You can view the CodePen HERE

HTML

<div id="slider">
  <ul>
    <li>
        <h1>Slide 1</h1>
        <a href="" class="slider__next">Go to slide 2</a>
    </li>
    <li>
        <h1>Slide 2</h1>
        <a href="" class="slider__next">Go to slide 3</a>
    </li>
    <li>
        <h1>Slide 3</h1>
        <a href="" class="slider__next">Go to slide 4</a>
    </li>
    <li>
        <h1>Slide 4</h1>
        <a href="" class="slider__next">Go to slide 5</a>
    </li>
    <li>
        <h1>Slide 5</h1>
        <a href="" class="slider__next">Go to slide 1</a>
    </li>
  </ul>  
</div>

CSS

#slider {
  position: relative;
  overflow: hidden;
  margin: 0 auto 0 auto;
  height: 100%;
  width: 100%;
  ul {
        position: relative;
    margin: 0;
    padding: 0;
    list-style: none;
    height: 100%;
    width: 100%;
... (CSS code continues)
    }
  }
}

jQuery

(jQuery code remains the same)

Answer №1

Definitely consider incorporating a variable into your code

let currentPosition = 0;

function moveRight() {
  if(currentPosition <= sliderCount) { // I'm not entirely sure if it's sliderCount or sliderCount - 1
     currentPosition++;
  } else {
     currentPosition = 0;
  }
  sliderItems.removeClass('active'); // removing all active classes
  $(sliderItems[currentPosition]).addClass('active'); // setting as active
}

In my humble opinion, this may not be the most efficient JavaScript since it could potentially benefit from being part of a prototype, but I believe it should still get the job done

Answer №2

If you want to make a small modification to your moveRight function, you can change it to remove the active class from the previously active slide and add it to the current slide:

  function moveRight() {
    var viewportWidth = $(window).outerWidth();
    $('#slider ul').animate({
      left: - viewportWidth
    }, 500, function () {
      $('#slider ul li:first-child').appendTo('#slider ul');
      $('#slider ul').css('left', '');

      // update active slide
      $('#slider ul li.active').removeClass('active');
      $('#slider ul li:nth-child(2)').addClass('active');
    });
  }

You can view an updated version on CodePen here.

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

I need clarification on the following: content:''

I have a question regarding this particular code snippet .store { display: block; position: relative; } .store:before, .store:after { display: block; position:absolute; content:''; } .store:before { background: url(store-before.png); ...

Sign up for the NPAPI Plugin directly through an SVG element

I've been exploring NPAPI Plugins for Chrome lately. The plugin has been designed to be scriptable and I have set up a custom MIME Type for it. In one of my HTML files, I included an embed tag with the 'type' attribute specifying the custom ...

Implement a procedure for printing a page once the columnize operation has been completed

Hello, I have run into a problem that I need help with. Currently, I am trying to print a page after the function "columnize" has finished its task. However, the print function is executing before the columnize function completes. How can I ensure that t ...

Card carousel rotation

Apologies for the vague title, I'm unsure how to properly label my issue. I have a section set up with cards, but I'm aiming to create something resembling a menu that functions like a carousel. Essentially, I want to include right and left arro ...

I'm curious why this is happening. Is it due to the default padding or margin property?

I am currently working on a website project. The genre navigation menu is located in the bottom left container, and I had to use a negative margin property to position the li elements correctly. However, there seems to be an unexpected top padding of aro ...

Interactive Javascript Dropdown Selection

I'm currently developing a registration page for a website and I've added a drop-down box that explains to users why we need their birthday. However, I seem to be having issues with my code. Take a look at the script below: <script language=& ...

Streamline event listeners with a pair of attributes

I am working with a function that requires one parameter: function magical(element){ ... } In my project, I have multiple click handlers attached to different elements and classes that are invoking this function: $('#div1').click(function(){ ...

Arrange floating elements in a three-column layout

Can anyone help me with a CSS solution to make boxes with different heights stack underneath each other neatly, similar to Tetris? Here's my code: CSS #page .equipeBox{ float:left; width:280px; padding:10px; margin:10px; backgro ...

Using a PHP Variable to Dynamically Generate an iFrame with a Custom URL

I am currently working on integrating an HTML form with a PHP form. The HTML form includes a dropdown menu with different URLs. Upon pressing the submit button, an iFrame is supposed to display the URL selected from the dropdown list. However, I've ...

What is the method to create a link that doesn't take up the entire page?

As a beginner in HTML, I have been working on a website for fun and facing an issue with buttons. When I add a button, the entire area becomes clickable, even if there is empty space around it. This means that you can click on the left or right side of the ...

Tips for replicating input fields that fetch information via ajax requests

My current code fetches data using AJAX from the database and allows for adding an unlimited number of text fields: <div class="input" id="itemRows"> <div class="clone"> <style> .txtHint { width:95 ...

Characteristics of touchend event

How can I capture all touchend events from mobile devices using the following code: $(document.body).bind('touchend', function (e) { var touch = e.touches[0]; // not working ... I am trying to retrieve the touch.screenX, touch.screenY, touch.cl ...

Customizing Bootstrap tooltip appearances with CSS

After successfully setting up Bootstrap 4.5.0, I decided to experiment with customizing the styles of tooltips. The code snippet below shows how I attempted this. Initially, I included the necessary stylesheets at the top of the page: <link rel=&q ...

Harnessing the power of Bootstrap 4: Adding text and icons to your <progress> bars

I'm attempting to add an icon overlay on a progress bar within Bootstrap 4 alpha. <progress class="progress progress-primary" value="100" max="100"> <i class="fa fa-check-circle-o"></i> </progress> The desired outcome shoul ...

Switching between videos can lead to an undesired bouncing effect on

Whenever I switch between my video thumbnails, there seems to be a slight bounce as the new video loads. To better understand this issue, check out this video: . <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

The code mistakenly sends an object in place of a numerical value

The script below is causing an issue where an object is being sent instead of a number. This is resulting in a console error: GET http://localhost:8080/new_prog_22/paginator.action?page=[object%20Object] 500 (Internal Server Error) The requirement ...

Steps for altering the primary color in PrimeNG__Changing the primary color

What is the most effective way to modify the default primary color for primeNG (saga-blue theme)? Altering --primary-color does not have the desired effect, as elements in node_modules/..../theme.css are styled using the main color hex rather than '-- ...

The parent navigation bar in HTML and CSS is hogging more space compared to its children

In the midst of my vuejs project, I have encountered an issue relating to the size of elements. Specifically, my header consists of a logo and a navbar. The navbar seems to be extending the size of the header unnecessarily. Upon inspection, I noticed tha ...

Script for automated functions

I have implemented 4 functions to handle button clicks and div transitions. The goal is to hide certain divs and show one specific div when a button is clicked. Additionally, the background of the button should change upon hovering over it. Now, I am look ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...