Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, with the first image being the only one displayed upon loading the page. However, clicking the next button immediately jumps from the first image to the fourth. Subsequently, pressing the previous button reveals images one, two, and three.

I am seeking guidance on how to ensure that the images are displayed in sequential order. The code snippet below illustrates my current approach.

https://jsfiddle.net/aj4tpu1z/

var prev = $('.prev');
var next = $('.next');

$('.li').each(function() {
    var left = $(this).prev();
    var right = $(this).next();

    next.on('click', function(){    
        left.hide();
        right.show();
    });

    prev.on('click', function(){
        left.show();
        right.hide();
    });
}); 

Answer №1

When you click on the .prev or .next buttons, all four images are affected because each image has a click handler attached to it. This results in all four handlers being executed, but only the last one affects the fourth image.

To fix this issue, you should calculate the next or previous image at the moment of the click. It is recommended to add a class to the current image and use that class for styling purposes.

var prev = $('.prev');
var next = $('.next');
var images = $('.images li');

function showImage( node ){
  node.addClass('active') // display specified node
      .siblings().removeClass('active'); // hide previously active node
}

prev.on('click', function(e){
  e.preventDefault(); // prevent scrolling to top or following the link
  
  var previousNode = images.filter('.active').prev();
  showImage(previousNode);
});
next.on('click', function(e){
  e.preventDefault(); // prevent scrolling to top or following the link
  
  var nextNode = images.filter('.active').next();
  showImage(nextNode);
});

$('.images li:first').addClass('active');
.images li{display:none;}
.images li.active{display:block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="prev">&#8592;</a>
<a href="#" class="next">&#8594;</a>


<div class="images">
  <ul>
    <li><img src="http://dummyimage.com/200x200?text=1" alt=""></li>
    <li><img src="http://dummyimage.com/200x200?text=2" alt=""></li>
    <li><img src="http://dummyimage.com/200x200?text=3" alt=""></li>
    <li><img src="http://dummyimage.com/200x200?text=4" alt=""></li>
  </ul>
</div>

Answer №2

You were facing a few issues, one of them being that the click handlers for next and prev were nested inside the .li class' .each() loop.

Check out this revised example (replaced images with numbers for demonstration purposes):

var prev = $('.prev');
var next = $('.next');
var num = 0;

$('.li').hide();
$('.li').eq(0).show();

next.on('click', function() {
  $('.li').hide();
  num++;
  if (num > 3) {
    num = 0;
  }
  $('.li').eq(num).show();
});

prev.on('click', function() {
  $('.li').hide();
  num--;
  if (num < 0) {
    num = 3;
  }
  $('.li').eq(num).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="prev">&#8592;</a>
<a href="#" class="next">&#8594;</a>


<div class="images">
  <ul>
    <li class="li">(Img 1)</li>
    <li class="li">(Img 2)</li>
    <li class="li">(Img 3)</li>
    <li class="li">(Img 4)</li>
  </ul>
</div>

If you prefer not to cycle from slide 4 back to slide 1 and vice versa, just let me know and I can adjust the code accordingly.

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

`Is there a way to choose several radio buttons with varying names using just one label?`

Is there a way to choose multiple radio buttons with different names using just one label? Here's an example of what I'm attempting to accomplish... <input id="1A" type="radio" name="first" value="A">firstA<br> <input id="1B" typ ...

Is it possible to use Primefaces tooltip to show at the bottom of the page

When I hover over the PrimeFaces tooltip, it displays at the bottom of the page. Here is my code and image link: <!DOCTYPE html> <h:html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com ...

"Troubleshooting the issue of jQuery failing to set data

Although it seems straightforward, I am puzzled as to why this code is not functioning properly. The selector is accurate, but for some reason the .faqContent div is not being updated with the data-height attribute. $('.faqItem .faqContent').eac ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

The sidebar vanishes when you move your cursor over the text contained within

My issue is that the side menu keeps closing when I hover over the text inside it. The "About" text functions correctly, but the other three don't seem to work as intended. Despite trying various solutions, I am unable to identify the root cause of th ...

Ways to create a vertically expandable full-screen design

I am currently working on designing a full-screen layout where the content adjusts based on the size of the footer. body { margin: 0; padding: 0; } .layout { height: 100vh; display: flex; flex-direction: column; background-color: yell ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

Bizarrely rapid transitions from standard to hovering appearance in CSS

After creating a custom styled button with a hover effect, I noticed an issue where if you happen to hover over a specific spot on the button, it quickly switches between its normal and hover states. https://i.sstatic.net/uPq1F.gif This is my code: but ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Learn how to troubleshoot and resolve a bug in the mobile Chrome browser that pertains to the position fixed feature

On the mobile version of Firefox, everything works perfectly. However, there seems to be a bug in Chrome with the fixed positioning. When scrolling, the header should change from absolute to fixed and the height should go from 65 to 35 pixels. Unfortunatel ...

Is there a way to invoke JavaScript functions from external files in an EJS template?

I've got this new Ship file to add. The script that populates the fleet dropdown menu is working perfectly: new.ejs file: <% include ../partials/header %> <div class="container"> <div class="row"> <h1 style="text-al ...

Dynamic Website (Link Relationships / Responsive Design / Content Rendering with CSS and HTML)

Hello everyone! My name is Mauro Cordeiro, and I come from Brazil. I am just diving into the world of coding and have been following various tutorials. Stack Overflow has been an invaluable resource for me in my learning journey! Aside from coding, I am a ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Executing the command in the Windows Command Prompt by utilizing an HTML button

When a button on my HTML page is clicked, I want to execute the command python abc.py in the Windows command prompt. The python file is stored at C:/abc.py. I'm looking for guidance on how to code the HTML page to achieve this functionality. Any assis ...

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

Adjust the zoom level when a location is detected using Mapbox

I have been reading through the leaflet documentation and it mentions using the maxZoom option for location, but I am having trouble getting it to work (http://leafletjs.com/reference.html#map-locate-options). Whenever a user uses geolocation on my websi ...

How can I remove the bouncing effect of the top bar in Chrome when scrolling in Three

There is a frustrating problem I am encountering on my website with the joystick control. Whenever I try to move my joystick down, Chrome triggers either the refresh dropdown or the top bar bounces and goes in and out of fullscreen mode. ...