What makes the addClass and removeClass functions in jQuery work correctly only when used with the alert function?

Attempting to create my own slider using jQuery, here's a working example:

$(document).ready(function(){


$(".carousel-indicators li").click(function(){
$(".carousel-indicators li").css("background-color", "transparent");
$(this).css("background-color", "yellow");
});


var active1, prev1, next1;

function rotateimages(){
active1 = $(".item.active");

if(active1.prev().length == 0) {
prev1 = $(".item").last();
prev1.removeClass("mytrans");
prev1.addClass("prev");
}
else {
prev1 = active1.prev();
prev1.removeClass("mytrans");
prev1.addClass("prev");
}

if(active1.next().length == 0) {
next1 = $(".item").first();
next1.removeClass("mytrans");
next1.addClass("next");
//alert();
}
else {
next1 = active1.next();
next1.removeClass("mytrans");
next1.addClass("next");
//alert();
}


active1.removeClass("active").addClass("prev mytrans");
next1.removeClass("next").addClass("mytrans active");
prev1.removeClass("prev mytrans");

}

setInterval(rotateimages, 3000);

});
.carousel-inner > .item > img,
  .carousel-inner > .item > a > img {
      width: 70%;
      margin: auto;
  }
  html, body {
  width: 100%;
  height: 100%;
  }
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style-type: none;
}
.container {
width: 768px;
margin: auto;
padding: 0 15px;
height: 100%;
}
#myCarousel {
width: 100%;
background-color: lightgray;
position: relative;
height: 100%;
}
.carousel-indicators {
position: absolute;
bottom: 20px;
left: 45%;
}
.carousel-indicators li {
list-style-type: circle;
display: inline-block;
width: 10px;
height: 10px;
border: 1px solid red;
border-radius: 10px;
cursor: pointer;
}

.mytrans {
transition: all 1s;
}
.carousel-inner .item {
position: absolute;
display: none;
}
.carousel-inner .item.prev {
left: -100%;
top: 0;
display: block;
}
.carousel-inner .item.next {
left: 100%;
top: 0;
display: block;
}
.carousel-inner .item.active {
left: 0%;
top: 0;
display: block;
}
.carousel-inner .left {
position: absolute;
left: 10%;
top: 50%;
}
.carousel-inner .right {
position: absolute;
right: 10%;
top: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner" role="listbox">

      <div class="item active">
        <img src="http://madaboutwords.com/wp-content/uploads/2010/05/one.png" alt="Chania" width="460" height="345">
        <div class="carousel-caption">
          <h3>Chania</h3>
          <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
        </div>
      </div>

      
    
      <div class="item">
        <img src="http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png" alt="Flower" width="460" height="345">
        <div class="carousel-caption">
          <h3>Flowers</h3>
          <p>Beatiful flowers in Kolymbari, Crete.</p>
        </div>
      </div>

      <div class="item">
        <img src="http://www.hotel-r.net/im/hotel/gb/number-three-22.png" alt="Flower" width="460" height="345">
        <div class="carousel-caption">
          <h3>Flowers</h3>
          <p>Beatiful flowers in Kolymbari, Crete.</p>
        </div>
      </div>

      <div class="item">
        <img src="http://www.hotel-r.net/im/hotel/gb/number-four-10.gif" alt="Flower" width="460" height="345">
        <div class="carousel-caption">
          <h3>Flowers</h3>
          <p>Beatiful flowers in Kolymbari, Crete.</p>
        </div>
      </div>
  
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>

The issue appears to be related to the fast addition and removal of the next class. Here's the problematic snippet:

else {
    next1 = active1.next();
    next1.removeClass("mytrans");
    next1.addClass("next"); 
    //alert();
}


active1.removeClass("active").addClass("prev mytrans");
next1.removeClass("next").addClass("mytrans active");           
prev1.removeClass("prev mytrans");

Question: How can I ensure that the styles of the next class are applied before it is removed by the removeClass function?

Answer №1

It is recommended to avoid using the removeClass/addClass functions in this manner.

An elegant solution in jQuery would be to toggle them like so:

active1.toggleClass('active');
active1.toggleClass('prev mytrans');
next1.toggleClass('next');
next1.toggleClass('mytrans active');

By utilizing this approach, you can create a function like the following, which is simpler to maintain and reduces code clutter compared to separate add/removes:

function toggleNext(){
    active1.toggleClass('active');
    active1.toggleClass('prev mytrans');
    next1.toggleClass('next');
    next1.toggleClass('mytrans active');
}

Furthermore, one drawback of removing/adding classes is that if jQuery cannot find the class to remove/add, your code will stop functioning properly.

http://api.jquery.com/toggleclass/

Answer №2

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" >
        $(document).ready(function () {


            $(".carousel-indicators li").click(function () {
                $(".carousel-indicators li").css("background-color", "transparent");
                $(this).css("background-color", "yellow");
            });


            var active1, prev1, next1;

            function rotateimages() {
                active1 = $(".item.active");

                if (active1.prev().length == 0) {
                    prev1 = $(".item").last();
                    prev1.removeClass("mytrans ").addClass(" prev");
                } else {
                    prev1 = active1.prev();
                    prev1.removeClass("mytrans ").addClass(" prev");
                }

                if (active1.next().length == 0) {
                    next1 = $(".item").first();
                    next1.removeClass("mytrans ").addClass(" next");
                    //alert();                      
                } else {
                    next1 = active1.next();
                    next1.removeClass("mytrans ").addClass(" next");
                    //alert();
                }


                active1.removeClass("active").addClass("prev mytrans");


                next1.removeClass("next").addClass("mytrans active");


                prev1.removeClass("prev mytrans");

            }

            setInterval(rotateimages, 3000);
        });


    </script>
    <style>

        .carousel-inner > .item > img,
        .carousel-inner > .item > a > img {
            width: 70%;
            margin: auto;
        }
        html, body {
            width: 100%;
            height: 100%;
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            list-style-type: none;
        }
        .container {
            width: 768px;
            margin: auto;
            padding: 0 15px;
            height: 100%;
        }
        #myCarousel {
            width: 100%;
            background-color: lightgray;
            position: relative;
            height: 100%;
        }
        .carousel-indicators {
            position: absolute;
            bottom: 20px;
            left: 45%;
        }
        .carousel-indicators li {
            list-style-type: circle;
            display: inline-block;
            width: 10px;
            height: 10px;
            border: 1px solid red;
            border-radius: 10px;
            cursor: pointer;
        }

        .mytrans {
            transition: all 1s;
        }
        .carousel-inner .item {
            position: absolute;
            display: none;
        }
        .carousel-inner .item.prev {
            left: -100%;
            top: 0;
            display: block;
        }
        .carousel-inner .item.next {
            left: 100%;
            top: 0;
            display: block;
        }
        .carousel-inner .item.active {
            left: 0%;
            top: 0;
            display: block;
        }
        .carousel-inner .left {
            position: absolute;
            left: 10%;
            top: 50%;
        }
        .carousel-inner .right {
            position: absolute;
            right: 10%;
            top: 50%;
        }


    </style>
    <div class="container">

        <div id="myCarousel" class="carousel slide" data-ride="carousel">
            <!-- Indicators -->
            <ol class="carousel-indicators">
                <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                <li data-target="#myCarousel" data-slide-to="1"></li>
                <li data-target="#myCarousel" data-slide-to="2"></li>
                <li data-target="#myCarousel" data-slide-to="3"></li>
            </ol>

            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">

                <div class="item active">
                    <img src="http://madaboutwords.com/wp-content/uploads/2010/05/one.png" alt="Chania" width="460" height="345">
                    <div class="carousel-caption">
                        <h3>Chania</h3>
                        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
                    </div>
                </div>



                <div class="item">
                    <img src="http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png" alt="Flower" width="460" height="345">
                    <div class="carousel-caption">
                        <h3>Flowers</h3>
                        <p>Beatiful flowers in Kolymbari, Crete.</p>
                    </div>
                </div>

                <div class="item">
                    <img src="http://www.hotel-r.net/im/hotel/gb/number-three-22.png" alt="Flower" width="460" height="345">
                    <div class="carousel-caption">
                        <h3>Flowers</h3>
                        <p>Beatiful flowers in Kolymbari, Crete.</p>
                    </div>
                </div>

                <div class="item">
                    <img src="http://www.hotel-r.net/im/hotel/gb/number-four-10.gif" alt="Flower" width="460" height="345">
                    <div class="carousel-caption">
                        <h3>Flowers</h3>
                        <p>Beautiful flowers in Kolymbari, Crete.</p>
                    </div>
                </div>

            </div>

            <!-- Left and right controls -->
            <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
            </a>
            <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
            </a>
        </div>
    </div>
</html>

This code has been provided for you to test.

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

index() jQuery function is not

Upon clicking on an element with the class 'sections', I expect to see an alert displaying its class index, however, it appears to be showing an incorrect number. For example, if I click on the first div element with the class 'sections&apo ...

How can you pass an authorization token in a Next.js post request when using Django REST framework?

Is there a way to successfully pass a Django authorization token in Next.js using Axios? I attempted this method, but encountered a 404 error. let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers ...

Testing the revised react component through unit testing with jest and enzyme

I am currently working on writing the test file for this code snippet. Here is my approach: import React from 'react'; import renderer from 'react-test-renderer'; // import { mount } from 'enzyme'; import LazyToastMessage from ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

"Encountering a 404 Not Found error while using Next.js and React-Query

I am currently facing a problem with setting up my Next.js project alongside an Express.js back-end. Initially, I set up the back-end as a regular one based on the documentation provided by Next.js. However, I am unsure if this approach is correct. My issu ...

What is the correct way to link to a SCSS file within a component's directory?

The structure of my directories is as follows: stylesheets ..modules ...._all.scss ...._colors.scss ..partials ...._all.scss ...._Home.scss ..main.scss In the _Home.scss file, I have the following: @import '../modules/all'; .headerStyle { c ...

Executing multiple operations with Graphql mutations

I am faced with a situation where I have 3 mutations to execute with 6 input parameters each. I need to send a mutation based on the value of certain status variables. How can I achieve this efficiently? mutation updateProfile( $input: UpdateProfileMuta ...

Issue with nested directive not triggering upon page load

I recently started working with AngularJS and came across an issue with nested directives. In my project, I have two directives: MainDir.js (function(){angular.module("mod").directive("mainDir", function(){ return { restrict: "E", scope: {}, ...

What are some debugging techniques for troubleshooting jQuery.post() requests when using JSON as the dataType?

Despite my efforts to rely solely on the search function, I am faced with an issue that I can't seem to resolve: Using jQuery, I call a PHP script to fetch values which are then used to update my HTML elements. Here is a snippet of my code: $.post( ...

What could be the reason for the failure of the .is(":hover") method?

Here is some code I'm using to fade out certain elements on a webpage if the mouse hasn't moved for a period of time: idleTime = 0; var idleInterval = setInterval(function() { idleTime++; if (idleTime > 1) { var isHovered = $ ...

Looking to generate iterative organic search code? I am currently working on parsing Log Format website files

My keyword-value pair search code is lightning-fast, but there's always room for improvement. You can check out the code on Fiddle. When a client calls HashCompactor's .add(keyword,datum) method, the keyword goes through a preprocessor that iter ...

The Content-Type header is missing in the Ajax request for json

In my PHP code, I generate valid JSON and set the content-type header to application/json in my development environment. However, when I deploy this code to an embedded web server, it functions properly but is unable to send the appropriate content-type he ...

Issue with logical operator ""!"" functionality in ejs file

Take a look at this code snippet: <% if( !title || title!=="login"){ %> <div class="dashboard-main-cont"> <div class="navigation-option"> <a class="btn btn-primary navbtn" href=& ...

What is the best way to align an image with the position of a div?

Looking for assistance on positioning an image to a div's position after it has been cloned. $(".raindrop1").clone().removeClass("raindrop1").appendTo("body"); $("img").css({"left": "div".x, "top": "div".y}); .shape{ border-radius: 50px; width: 10p ...

reveal or conceal content on hover of mouse pointer

I am currently working on a section that functions like jQuery tabs, but instead of requiring a click to activate, I want it to work on mouse hover. The current implementation is somewhat buggy - when hovering over a specific section, it displays as expe ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Is there a restriction on the amount of data that can be

I have provided the code snippet below for reference: <System.Web.Services.WebMethod()> _ Public Shared Function LinkedUSNs(ByVal usn As String, ByVal requester As String, ByVal reason As String, ByVal terminalip As String, ByVal strCon As Strin ...

Altering data in a concealed dynamic HTML form

I have a hidden form on my webpage that gets populated dynamically when a button is clicked. I want to be able to change the values within this form dynamically. Initially, the form looks like this: <form id="zakeke-addtocart" method="pos ...

Elevate your Material UI experience by setting a maximum height for TableBody and enabling vertical scrolling for a seamless

I'm looking to utilize Material UI to set a maximum height of 500px for the TableBody within my Table. If there are rows that exceed this height, I want the TableBody to scroll vertically while keeping the TableHead fixed in place. https://i.sstatic. ...

unable to locate the ID of the actionlink that was clicked

I'm facing an issue and I require a jQuery script to identify which anchor tag with the class "edit" has been clicked in my existing jQuery code. Since there are multiple edit buttons, I need to determine the specific ID of the clicked button. Apprec ...