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

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

A curious phenomenon observed in the behavior of the jQuery offset() method

Once I executed the following code snippet multiple times: $view.offset({ left : X, //X remains constant top : this.y }); console.log($view.offset()); //displays expected output I noticed (using Firebug) that the HTML code looked like this: <di ...

Strange issue with Firefox when utilizing disabled attribute as "disabled"

I found a curious bug in Firefox: Check out (unfortunately not reproducible in jsfiddle) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> < ...

What is the reason behind the issue of an infinite loop being resolved by including additional arrow function parentheses?

I'm currently using React for my project, and I've encountered an issue with the setState hook. Below is a snippet of my code: //state and handle function const [activeStep, setActiveStep] = React.useState(0); const handleStep = (index) => ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Border extends across two separate rows

Let me illustrate my issue with a specific example where I am utilizing a single column with a rowspan: <table border="1" style="width:300px"> <tr> <td rowspan="2">Family</td> <td id="jill">Jill</td> <td>Smi ...

AngularJS can retrieve the selected value from a select tag

<select ng-model="data.person"> <option value="1" selected="">1 pax</option> <option value="2">2 pax</option> </select> The ng-model above returned "1 pax," but how can I retrieve ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

How do I resolve the issue of a non-iterable 'int' object?

1 How can I troubleshoot the error that is popping up? I believe the issue may be related to it being a dictionary. Any suggestions on how to fix this problem? views search(request): if "q" in request.GET: querystring = request.GET.get(" ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

Firebase authentication encountered an error due to a network request failure

Utilizing firebase Hosting to host my website, I am encountering a persistent error when attempting to login using email/password. This is the JavaScript code that I am using: window.onload = () => initApp(); //Initialize screen function initApp(){ ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

Retrieve some delicious cookies by making an AJAX request

I have been attempting to retrieve cookies that were set at the backend following an AJAX post, and despite trying various solutions I have come across, I am still unable to find where I may be going wrong. Below is a code snippet for extracting headers f ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

Create a new JavaScript object by parsing JSON data

I am looking to achieve the following: var my_data = { x : 'orange', y : 2 } function object(data){ this.x = 'banana'; this.y = 3; this.z = 'default value'; } once I have executed: var new_instance = ob ...

How to prevent a directory from being copied in webpack within Vue CLI

Currently, I am working on a Vue3 project created using Vue CLI 5.0.1 In my setup, there is a public folder that contains static assets necessary for serving the application. However, this folder is quite heavy, around 1GB in size. Whenever I run the npm ...

Use JavaScript to input array elements into a selection of cells in Excel

At this moment, the loop I am executing successfully retrieves the necessary values. However, I am facing challenges when it comes to inserting these array values into a range of cells. I keep encountering the following error message: Error message: "The ...

Is it possible to disable the pointer event on the parent element only in CSS

Here's the structure I'm working with: <div class='offline'>some text <button class='delete'>Delete</button></div> I want to disable the div using pointer-events: none, but still keep the button activ ...

Unable to open new tab using target _blank in React js production build

After attempting to access the link, a 404 error appeared in the live version of react js and triggered an error on the firebase hosting platform. <Link target='_blank' to={'/property-details?id='some_id'}/> ...