Repeatedly using jQuery to add elements twice

When I run this code, every time I click the '#right' button, the #slide increments by 2 instead of just 1. For example, if there are a total of 6 elements, it displays the 1st, 3rd, and 5th elements.

    var currentSlide=2;
    var totalSlides=document.getElementById("slider").childElementCount;
    $("#right").click(function()
    {

        for(i=1;i<=totalSlides;i++) {
            $("#slide"+i).css("display","none"); // hide all elements
        }
        $('#slide'+currentSlide).css("display","block"); // displaying only one element (which gets incremented by 2)
        
        currentSlide=(currentSlide+1)%totalSlides;
    });

If I use specific numbers like ('#slide'+2) instead of ('#slide'+currentSlide), I get the right results. However, I want to do this dynamically...

Thanks!

Answer №1

Instead of using a for loop, you can utilize jQuery's ability to return a collection of elements in an array without the need for additional iteration.
To achieve this, simply pre-increment and use the modulus operator (%) on your counter.

http://jsbin.com/uhiyew/1/edit

var present=2;
var $childrens = $("#slider > *");
var total_slide = $childrens.length;

$childrens.eq(present).show();


$("#right").click(function(){

     $childrens.hide() // hide all elements
        .eq(++present%total_slide).show(); // show desired

});

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

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...

Add a stylish border to your image within a container of fixed width

I am facing a challenge with a fixed width DIV element. Inside this element, there is a second DIV containing only an IMG element. My goal is to add a border to the image without exceeding the boundaries of either of the enclosing DIV tags. Solution #1: ...

Is there a way to dynamically fetch and showcase chosen values from linked dropdown menus without needing to refresh the page?

My challenge lies in displaying the selected options from two chained select boxes without the need for a page refresh. Currently, a PHP function retrieves and displays the values when users click on a button, but I want to achieve this dynamically using ...

Element is not being overlapped by higher z-index

#navbarContentHamburger { background-image: url(../img/657904-64.png); background-size: contain; z-index: 3; position: fixed; width: 22px; height: 20px; top: 7.7px; left:8px; } .open { width: 4% !important; transiti ...

Alter the hue of the div

Having trouble with this code snippet: function red(opt) { var sqr; sqr="r"+parseInt(opt); hilight_css = {"background-color":"#f00"}; $(#sqr).css(hilight_css); } I am calling the function like so: red(questions); The variable question ...

Javascript time intervals run rapidly during tab changes

I am facing an issue where my neck is constrained at regular time intervals. I have a function that helps me calculate time one second at a time: Header.prototype= { time_changed : function(time){ var that = this; var clock_handle; ...

Concerns with "redirecting links script"

Check out this code snippet: <script> if(document.location.href.indexOf('https://customdomain.com/collections/all?sort_by=best-selling') > -1) { document.location.href = 'https://customdomain.com/pages/bestsellers'; } </sc ...

What is the method for positioning a logo image, phone number, and location above the navbar using bootstrap?

I just started learning Bootstrap and I am trying to add a logo image, location image with address, and phone number with text above the navigation bar. I want all these elements to be centered on the page. However, my current attempt is not achieving the ...

Alternating CSS Designs for Displaying Multiple Mysql Query Results

I have a website where users can search for a specific product in their location, and the site will display a list of results. if(isset($_POST['zip'])){ $qry="SELECT business_id FROM ".TBL_BUSINESS." WHERE zip LIKE '%".$_POST['zip&apos ...

The legend in the fieldset is not displaying correctly due to overflow issues

Within my fieldset, there is a legend structured as shown below: <fieldset class="fieldsetStyle"> <legend class="fieldsetLegendStyle"> <div> <h:outputText value="#{msgs.LABEL_AJOUTER_U ...

Organizing a list based on Date property in C# versus implementing jQuery for the task

Currently, I am working with a List<Event>. Each Event object contains a Date property. I have successfully bound this list to an asp:repeater, resulting in a simple list of event titles that look like: event 1 event 2 event 3 event 4 event ...

Picture is not appearing on web browser within Node application

Recently, while working with Visual Studio Code, I decided to incorporate an image into my Node project. After downloading the image from the internet and placing it in the directory, I renamed it to 'file_2.jpeg'. I then included <img src = " ...

Retrieve the values of the recently selected options in a multiple selection

I am trying to retrieve the last or most recently selected option value from a dropdown menu. In my Django code, I have attempted the following: <script type="text/javascript> django.jQuery(document).ready(function(){ django ...

Align the content at the center within a Bulma column

I am working with multiple columns, each column containing a circle in the CSS depicted as a font awesome icon centered within it. However, I am facing an issue where the circle remains aligned to the left while the text itself gets centered. HTML <di ...

Generate an array of objects based on the attributes of img elements, extract their values, and display them using jQuery

I currently have a fullscreen plug-in that works with static URLs, but I want to switch to using dynamic image data generated by a CMS on the page. Here is a snippet of the HTML output from the CMS: <ul class="large-gallery"> <li> <a href ...

Navigating horizontally with buttons in VueJS

I am searching for a way to implement horizontal scrolling using buttons in VueJS. The idea is to have a container with multiple divs arranged horizontally, and I wish to navigate through them using the buttons. If you want to see a similar solution using ...

Display issue with ul and li elements in Safari browser causing menu to appear incorrectly

Although I am new to CSS, I managed to create a menu on my website that hovers over the background video successfully. It is a basic menu using a ul with li elements and it appears as intended in all browsers except Safari. In Safari, the menu items stack ...

When the user clicks, display one div and conceal the others

https://codepen.io/leiacarts/pen/PoqRxNZ I need assistance with two specific tasks related to my website layout. Firstly, I am struggling to ensure that images displayed in the red sections remain constrained and automatically resize within the content di ...

Typo3 Issue: Jquery Ajax Loading Homepage Issue

Here is the issue I am facing: I recently inserted the following code into a page within Typo3 (.../index.php?id=18). The content type of the element is pure html (special->html). <select name="testvariable" id="testvariable"> <option value ...

On the iPad, CSS styling will not be visible if an element's width exceeds 920 pixels

I recently developed a website optimized for monitors, but when I viewed it on an iPad, the right corner was missing some CSS styles. Take a look: Here is the HTML code: <div id="nav-top"> <div class="wrapper"> <!-- To ...