Switching classes will not alter the current class

Having an issue with using toggleClass in jQuery.

Check out the code snippet below:

$(".guzik").click(function() {
    $("#third").toggleClass('.pillar-animation-two');
});                  

function test(){
    document.getElementById('third').className('.pillar-animation-two');
}
.pillar {
    width:50px;
    height:10px;
    background-color:red;
    margin-top:5px;
}

.pillar:nth-child(1) {
    margin-top:0;
}

.pillar-animation-one {
    transform:rotate (10deg);      
}

.pillar-animation-two {
    transform:rotate (20deg);
    width:10px; 
    height:10px;
    background-color:red;
    margin-top:5px;      
}

.pillar-animation-three {     
    animation-name:three;
    animation-duration:1s;
}
   
@keyframes three {
    0%{transform:rotate(0deg);}
    100%{transform:rotate(40deg);}
}

.button {
    margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hamburger">
    <div class="pillar"></div>
    <div class="pillar"></div>
    <div class="pillar" id="third"></div>
</div>
<button class="button" type="button" onclick="test()"> Click me !</button>

Any ideas about what I might be doing wrong? Even addClass isn't working, so feeling quite lost here. Tried creating a JS function but that's not helping either.

Please point out where the mistake might be located.

Thank you.

Answer №1

Eliminate the period . before toggleClass. The function only requires the name, as the period indicates it is already a class.

$("#third").toggleClass('.pillar-animation-two');

Adjusted code:

$("#third").toggleClass('pillar-animation-two');

Answer №2

When using the toggleClass method, you do not need to include a dot (.) before the class name.

$(".button").click(function() {
  $("#third").toggleClass('pillar-animation-two');
});

function changeClass() {
  $('#third').toggleClass('pillar-animation-two');
}
.pillar {
  width: 50px;
  height: 10px;
  background-color: red;
  margin-top: 5px;
}
.pillar:nth-child(1) {
  margin-top: 0;
}
.pillar-animation-one {
  transform: rotate (10deg);
}
.pillar-animation-two {
  transform: rotate (20deg);
  width: 10px;
  height: 10px;
  background-color: red;
  margin-top: 5px;
}
.pillar-animation-three {
  animation-name: three;
  animation-duration: 1s;
}
@keyframes three {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(40deg);
  }
}
.button {
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hamburger">
  <div class="pillar">
  </div>
  <div class="pillar">
  </div>
  <div class="pillar" id="third">
  </div>
</div>
<button class="button" type="button" onclick="changeClass()">Change Class!</button>
<button class="guzik">Click Here</button>

Answer №3

Take a look at this solution!

$(".pillar").click(function()
{
  $(".pillar").toggleClass('pillar-animation-two');
});
                     

function test(){
    $("#third").toggleClass('pillar-animation-two');

}
.pillar
{
  width:50px;
  height:10px;
  background-color:red;
  margin-top:5px;
}
.pillar:nth-child(1)
{
  margin-top:0;
  
}

.pillar-animation-one
{
  transform:rotate (10deg);
  
}
.pillar-animation-two
{
  transform:rotate (20deg);
  width:10px; 
  height:10px;
  background-color:red;
  margin-top:5px;
  
}

.pillar-animation-three
{
 
  
  animation-name:three;
  animation-duration:1s;
  
  
  
}
@keyframes three
{
    0%{transform:rotate(0deg);}
    100%{transform:rotate(40deg);}
  }

.button
{
  margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hamburger">
<div class="pillars">
  </div>
<div class="pillars">
  </div>
  <div class="pillar" id="third">
  </div>
</div>
<button class="button" type="button" onclick="test()"> Click here !</button>

Answer №4

When working with Vanilla JS, keep in mind that className is not a method but a property of an element. To add a class name properly, use the following syntax:

document.getElementById('third').className = 'pillar-animation-two';

This will replace all existing classes for the specified element.

If you prefer to toggle a class instead, you can achieve this with jQuery by using the toggleClass() function as shown below:

$(".button").click(function() {
  $("#third").toggleClass('pillar-animation-two');
});

View Demo on Fiddle

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

Guide to retrieving the second value variable in an array based on the selected dropdown option within a controller

In my controller, I am trying to extract the second value in an array list that a user selects from a dropdown so that I can perform mathematical operations on it. $scope.dropdown = [ {name:'Name', value:'123'}] When a user chooses "N ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

Is there a way to design a side menu navigation bar that reveals items by sliding them out to the right?

Currently, I am attempting to emulate a website as practice since I am relatively new to HTML, CSS, and JavaScript. As part of this exercise, I have designed a navigation bar on the left side (similar to the example provided for food items). The objectiv ...

Steps for redirecting from a URL containing location.hash to a different page

Recently, I decided to move a section of one of my webpages from dummy.com/get-started/#setup to its own page at dummy.com/setup. After making this change, I went ahead and deleted the old /get-started page on my website. Many people have bookmarks saved ...

What function does the sx prop serve in Material UI?

<Container style={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Container> <Container sx={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Cont ...

Having trouble with AJAX within AJAX not functioning properly?

Similar to the Facebook commenting system, I am aiming for comments to be appended to previous ones and displayed all at once. However, currently the comments only show up after the page is reloaded. Please Note: Each post initially loads with just two co ...

What is the best way to create a line break at the maximum width point?

I am currently working on a code that dynamically receives variables and concatenates them with an underscore: var text = product + "_" + someOtherInfo; After combining the variables, I need to display this text inside a div element. div { max-width ...

Implementing time and date formatting in Highcharts

I'm almost finished with my highchart, but I am struggling to make the datetime/timestamp display correctly. I'm not sure if it's an issue with the format for the xAxis or the series. https://i.sstatic.net/br0Xn.png Here is my data: [{"x": ...

Notification that appears when accessed on a mobile device

I have encountered an issue with my website where mobile users are being continuously redirected to the mobile site due to the hosting of the sites in different places preventing the use of cookies to remember the redirection. As a result, a loop occurs. ...

A guide on using jQuery to cycle through every row of every table on an HTML page

I am trying to figure out the correct syntax for nesting two loops within each other in jQuery. The first loop should iterate over each table in an HTML page that does not have any IDs or classes, while the second loop should go through each table row of t ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

"Step-by-step guide on incorporating and executing a jQuery function, along with integrating it into PHP code for seamless

I recently created a function to manipulate form fields using jQuery: (function () { jQuery.fn.field = function (inputName, value) { if (typeof inputName !== "string") return false; var $inputElement = jQuery(this).fin ...

Despite using twitter bootstrap, the elements on my webpage are still overlapping one another

While implementing Twitter Bootstrap on my website, I encountered a problem where elements start overlapping if the window size is reduced. This issue does not look appealing, and I expected Twitter Bootstrap to ensure that my website is fully responsive a ...

How do I transfer a constant from a vanilla JavaScript file containing DOM elements to my Express server?

Implementing Firebase authentication on my website, I'm looking to pass the user const into Express for routing purposes. Here's the function responsible for creating a new user: const signupForm = document.getElementById('signup'); if ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Activate single elements one at a time

If you want to understand the question better, take a look at my code on jsfiddle. Each Div contains only one link. When you click on the link, it sets the Div to active and shows a hidden Div within it. Clicking the link again toggles the active style an ...

What is the compatibility like between Internet Explorer and NodeJS, JavaScript, and HTML/CSS in the present day?

I need help deciding between developing a desktop application using Electron or opting for a WebApp. The majority of my customers use Internet Explorer, with around 70% using older versions. I want to ensure that the app does not run slowly, crash, or la ...

jQuery's show/hide function exhibiting inconsistencies when checking or unchecking

I have implemented a feature on my webpage where there is a field for previous surgeries with certain elements. The goal is to display the previous surgery elements only if the "previous surgery" checkbox is checked. Below is a snippet of the code I'm ...

Using the d3.js library to format numbers displayed in tooltips

I'm currently working on a d3 graph that includes a tooltip showcasing the number of units. My goal is to format these numbers in a way that they appear as "Units: 225,247" rather than the current format of "Units: 225247." var div = d3.select(' ...

ASP.NET WebMethod sends the entire webpage back to JQuery ajax requests

I've been working on a web application that involves calling an ASP.NET WebMethod from jQuery when a textbox is clicked. However, I'm encountering an issue where the WebMethod is returning the entire ASPX Page instead of just the values I need. H ...