The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in:

<div id="toggle" class>
...

rather than:

<div id="toggle" class="on">
...

I've been trying to solve this issue for about 2 hours now, searching through various posts, but none seem to address my specific problem even though the outcome is the same.

The initial part of the JavaScript code is just animating a loading screen and then hiding it.

$(function() {
  $(".loader_gif_wrapper").fadeOut(1000, function() {
    $(".slider").animate({
      width: ["0%", "swing"]
    }, 2000, function() {
      // Animation complete.
      $(".loader_page_wrapper").hide();
      
      $("#toggle").click(function() {
        $(this).toggleClass('on');
      });
    });
  });
});
#toggle {
  position: absolute;
  left: 3rem;
  top: 3rem;
  z-index: 10000;
  width: 40px;
  height: 40px;
  cursor: pointer;
  float: right;
  transition: all 0.3s ease-out;
  opacity: 1;
  visibility: visible;
}

#toggle .span {
  height: 3px;
  background: #ffffff;
  transition: all 0.3s ease-out;
  backface-visibility: hidden;
  margin: 5px auto;
  border: solid 1px $tres;
} 
#toggle.on #one {
  transform: rotate(45deg) translateX(2px) translateY(4px);
}

#toggle.on #two {
  opacity: 0;
}

#toggle.on #three {
  transform: rotate(-45deg) translateX(8px) translateY(-10px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="toggle">
  <div class="span" id="one">One</div>
  <div class="span" id="two">Two</div>
  <div class="span" id="three">Three</div>
</div>

Answer №1

It is important to place the event declaration outside of the callback function to ensure that the event will be attached regardless of whether the callback is reached or not:

$(function() {
  $(".loader_gif_wrapper").fadeOut(1000, function() {
    $(".slider").animate({
      width: ["0%", "swing"]
    }, 2000, function() {
      // Animation complete.
      $(".loader_page_wrapper").hide();
    });
  });

  $("#toggle").click(function() {
    $(this).toggleClass('on');
    //$("nav").toggle();
  });
});

EXAMPLE OF WORKING CODE

$(function() {
  $("#toggle").click(function() {
    $(this).toggleClass('on');
  });
});
#toggle {
  position: absolute;
  left: 3rem;
  top: 2rem;
  z-index: 10000;
  width: 40px;
  height: 30px;
  cursor: pointer;
  float: right;
  transition: all 0.3s ease-out;
  opacity: 1;
  visibility: visible;
  background-color: green;
}

#toggle .span {
  height: 3px;
  background: #ffffff;
  transition: all 0.3s ease-out;
  backface-visibility: hidden;
  margin: 5px auto;
  border: solid 1px;
  border: solid 0px;
}

#toggle.on #one {
  transform: rotate(45deg) translateX(2px) translateY(4px);
}

#toggle.on #two {
  opacity: 0;
}

#toggle.on #three {
  transform: rotate(-45deg) translateX(8px) translateY(-10px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="toggle">
  <div class="span" id="one"></div>
  <div class="span" id="two"></div>
  <div class="span" id="three"></div>
</div>

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

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Why does the <select> dropdown flash when I select it?

Currently utilizing Angular 1.3 and Bootstrap 3.3.x CSS without the JS functionality. There is also an interesting animated GIF embedded within. <div class="form-group"> <div class="col-lg-3"> <label clas ...

Sending the selected multiple values to the controller function

I am facing an issue with sending the selected values of a multi-select list to an Action in my Controller. Despite verifying that val() shows an array of selected values like ["33","175"] when printed to the console, the Action's argument always ends ...

Detecting the preferential usage of -webkit-calc instead of calc through JavaScript feature detection

While it's commonly advised to use feature detection over browser detection in JavaScript, sometimes specific scenarios call for the latter. An example of this can be seen with jQuery 1.9's removal of $.browser. Despite the general recommendatio ...

How can I make a dropdown menu appear when I select a checkbox?

Is it possible to have a dropdown menu with changing options appear when I click on a checkbox using HTML and JavaScript? I have experimented with some code snippets in JavaScript as a beginner, but I am unsure if they are needed here. Is there an altern ...

Using SVG files in NextJS

I'm encountering an issue while trying to import an SVG file in a NextJS project. The error message I keep getting is: ./assets/aboutimg.svg 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, ...

Can you explain the purpose of this.element within a jQuery function?

Recently, I came across an enlightening explanation of the jQuery UI combobox by Jörn Zaefferer. If you're interested in checking it out as well, here's the link. One particular line of code that caught my attention was: var select = this.eleme ...

Axios fails to capture and transmit data to the client's end

I created a backend using Express to retrieve Instagram feed images and then send their URLs to my front end, which is built with ReactJs. When I fetch the image URLs with instagram-node and send them to the front end, everything functions as expected. How ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

Transform Vue military time to regular time format

I am retrieving the arrivalTime from todos.items. As I fetch the arrivalTime, it is sorted using the sortedArray function(), which converts the times to military time. Is there a way to change the sorted military time values to standard time format after s ...

The script fails to load when utilizing jquery/ajax

After the page loads, I am attempting to dynamically add a script into a div using ajax/jquery. This particular script is sourced from a CPM network and is responsible for loading a banner. However, when I try to load this script through ajax post-page lo ...

Buttons in Jquery refusing to execute click function

I'm attempting to dynamically change the text below my form based on the user's selection of either 'yes' or 'no' through 2 radio buttons. The function getCats is responsible for setting catVal to the chosen radio button value ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

Guidelines for combining inner objects with their parent in Javascript

I need assistance with using the filter function in Angular.js because it's not working on objects. Is there a way to merge a nested object into its parent using Javascript? For example, I have the following data structure: { "data" : [ { "ch ...

What distinctions are there between placing a `<link rel="stylesheet" href=..video.scss>` in the index.html versus utilizing `import '../video.scss'`?

As a newcomer to React.js, I've observed that there are different ways to include stylesheets in a React Component. Some developers use the import method like this: import '../../styles/video.scss while others prefer to link the stylesheet dire ...

I'm struggling to center my navigation bar and adjust its size properly, causing the page to overflow

I am facing some issues with my navigation bar. I am unable to adjust its size or position it at the center of the page. Additionally, despite setting the body width and height to 100vw and 100vh respectively, I am able to scroll both vertically and horizo ...

Setting up a React Package by reinstalling a git repository

While immersing myself in learning React JS, I decided to create a git repository containing React components that could be exported and used or installed as a package in a separate React application. I developed some UI Components in a git repository and ...