jQuery's remove/add class functionality seems to only function once

I haven't had much sleep and I'm not sure if toggleClass will work for this situation. Here is the code I currently have:

$(document).ready(function() {
    // Slide Mobile Filter Sidebar Onto Screen
    $('#showFilters').on('click', function () {
        $('.filter-sidebar--mobile__close').attr('class', 'filter-sidebar--mobile__close');

        $('.filter-sidebar--mobile')
            .removeClass('slide-out-right is-hidden') 
            .addClass('slide-in-right '); 
    });

    // Slide Mobile Filter Sidebar Off Screen
    $('.filter-sidebar--mobile__close').on('click', function() {
        $('.filter-sidebar--mobile')
            .addClass('slide-out-right') 
            .delay(380) 
            .queue(function() {
                $('.filter-sidebar--mobile').addClass('is-hidden'); 
            });

        // Hide Close Button for Mobile Filter
        $('.filter-sidebar--mobile__close').attr('class', 'filter-sidebar--mobile__close is-hidden');
    });
});

This code only works through one full cycle.
What happens is;

  • On load: no mobile filter(as expected)
  • Click #showFilters button
  • .filter-sidebar--mobile slides in from the right (as expected)
  • Click .filter-sidebar--mobile__close, .filter-sidebar--mobile slides out to the right (as expected)
  • Click #showFilters button again
  • .filter-sidebar--mobile slides in from the right (again as expected)
  • Click .filter-sidebar--mobile__close, .filter-sidebar--mobile animation plays, however this time does not stay hidden



Demo: https://jsfiddle.net/mfayv8fu/

Answer №1

According to the JQuery Documentation :

It is important to remember that when adding a function using .queue(), we must make sure that .dequeue() is called at some point so that the next function in line can be executed.

Therefore, in the queue callback, your code should look like this:

$('.filter-sidebar--mobile')
    .addClass('is-hidden')
    .dequeue();

Alternatively :

Starting from jQuery 1.4, the function being called receives another function as its first argument. When invoked, this function automatically dequeues the next item and allows the queue to progress. We use it in the following way:

.queue(function(next) {
    $('.filter-sidebar--mobile').addClass('is-hidden'); // Hide after animation completes
    next();
 });

Answer №2

It appears that you forgot to include the dot sign when querying your classes

  $('filter-sidebar--mobile').addClass('is-hidden'); 

Please update it to

  $('.filter-sidebar--mobile').addClass('is-hidden'); 

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

Explain the mechanics of the calculator code operating by inputting numerical values in a string format

Recently, I attempted to create a calculator in JavaScript and encountered a requirement to place the button values within single quotes as if they were strings. It's fascinating how these string values can work alongside operators to produce the desi ...

Tips for automatically refreshing a div in Drupal

I'm currently working with Drupal and I'm looking to update a specific field every X seconds without having to refresh the entire page. My current approach involves using the following code: <script> var refreshId = setInterval(function ...

Displaying text on an image when hovering over it

I have tried various solutions that I came across, but none of them have been successful so far. My goal is to display dynamic text over an image when the user hovers over it. Additionally, I would like to change the hover color. Currently, the text is alw ...

Issue within the application causing a sudden shutdown

I have been encountering an application error in my android phonegap app. The issue arises when I transition from one page to another page, resulting in the following message: "A network error occurred.(file:///android_asset/www/home/home.html?userid=91 ...

How to dynamically insert a key into an array by locating a specific value in AngularJS

I need help adding a new key to a JSON array by searching for a specific key value. For example JSON:- [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", ...

dealing with a situation where the call to the getElementsByTagname method returns null

Here is a snippet of JavaScript code that I am working with: <script language="JavaScript" type="text/javascript"> var sendReq = getXmlHttpRequestObject(); var receiveReq = getXmlHttpRequestObject(); var lastMessage = 0; var mTimer; ...

how do I modify my JavaScript code to achieve the desired outcome

How can I program a button to disable after being pressed 10 times in less than a minute, but continue counting if not pressed for 1 minute? function buttonClicked() { if (totalCount + accCounter > 9) { document.getElementById("btn").disabled = ...

What is the best way to generate a nested object arrangement using a path (series of keys)?

I have a challenge of creating nested objects from arrays of strings to store the sequence of input strings. Originally, I was only generating chains with a depth of 2, but now I need to expand this capability to create higher-depth chains. Essentially, I ...

Removing a Django object via AJAX or JavaScript with a confirmation prompt

Greetings! I am looking to implement a feature in Django where I can delete an object using AJAX or JavaScript with a confirmation message upon clicking the delete button. However, I am struggling to complete the AJAX request. Here is the code in views.py ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Using Three.js to transfer one object's rotation to another object

I have been attempting to transfer one object's rotation to another with no success using the following methods: //The first method rotates much faster than the original object's rotation boxme1.rotateOnAxis(new t.Vector3(0,1,0), cube.rotation.y ...

Header problem in Internet Explorer 7

I have been using IE-tester and Adobe Browser Lab to check the IE Compatibility, but a friend suggested using IE Developer Toolbar and switching the IE Browser Mode to IE7. The whole website looks different compared to IE Tester and Adobe Browser Lab. Can ...

Issue with Angular table display cell overloading(produces excessive rendering of cells)

In my project, I am working with 3 arrays of data - DATA_CENT, DATA_NORTH, and DATA_WEST. Each of these arrays contains another array called data, which I need to extract and display in a table format. For each new column, I create a new table and then po ...

Issue with AngularJS binding not updating when the initial value is null and then changed

I am encountering an issue with my binding not updating, and I have a hypothesis on why it's occurring, but I'm unsure about how to resolve it. Within my controller, there is a company object that includes a property called user, which may or ma ...

The CORS policy has blocked access to XMLHttpRequest at 'http://localhost:8080/' from the origin 'http://localhost:3000'

There seems to be an issue with the CORS policy blocking access to XMLHttpRequest when trying to send a post request from NuxtJS frontend to a Node server hosted on localhost:3000. Despite using CORS in the app, the error persists, preventing insertion of ...

Issue detected in JSONP request EXCLUSIVELY BY Firefox extension

It's strange that the error I'm experiencing only occurs in the Firefox extension I've linked at the bottom of this post. I've tried reproducing the error in other settings, but it just doesn't happen. Here is the AJAX request I&a ...

Restrict the number of rows in a real-time search JSON data by utilizing the $.each method

Is there a way to limit the number of rows returned in live search JSON data through URL? I attempted to count the table rows and return false, but it did not work. Any suggestions on how to achieve this? $(document).ready(function() { $.ajaxSetup ...

Displaying a loading indicator as content loads within the iframe

How to Display a Loading Indicator During Content Loading Within an iFrame: 1) When a postback or submit event occurs within a form inside the iFrame ...

`What is the method for retrieving controller functions in karma test scenarios?`

I am a beginner when it comes to Angular and Karma. Here is an example of a controller in Angular: angular.module('login').controller('LoginCtrl', function ($scope, $location) { var vm = this; $scope.text = 'Hello World!& ...

leveraging ajax with jquery and objects

$sql="SELECT * FROM seat WHERE type=$type AND seat=$seat"; $getseats=Yii::$app->db->createCommand($sql)->queryAll(); echo json_encode(array('status' => TRUE, 'getseats'=>$getseats)); die; Here, we are retrieving ...