Brainmaniac
Brainmaniac

Reputation: 2556

toggleClass only adds 'class' as attribute to HTML element - not the acctuall class

I have an odd problem. I have used toggleClass before and had it working nicely. Now however only the 'class' attribute gets added to the element but no actuall class. Like this:

$("#slideButtonMenu").click(function(){
  $("#sidebar").toggleClass("slideLeft");
});
.slideLeft {
  left: -220px;
}

This is what I get while inspecting the element. Before click on "#slideButtonMenu":

<aside id="sidebar"> == $0

When/after clicking the button:

<aside id="sidebar" class> == $0

Wanted outcome after first click:

<aside id="sidebar" class="slideLeft"> == $0

I don't really know what the == $0 means but I don't think it affects this. If I change toggleClass to addClass it successfully adds the class... but then I obviously can't slide the menu back out again.

Upvotes: 1

Views: 580

Answers (1)

Brainmaniac
Brainmaniac

Reputation: 2556

As @Rory McCrossan and @Turnip suggested my click was binded wrongly.

The answer was to add unbind(), like so:

$("#slideButtonMenu").unbind().click(function(){
    $("#sidebar").toggleClass("slideLeft");
});

Works now!

EDIT: According to @Turnip this should not be needed if everything with my code was done correctly but for now I am just gonna YOLO and go with this for my POC tmrw.

EDIT2: Ok, found the wrongings. I did load this script twice:

$("#slideButtonMenu").click(function(){
    $("#sidebar").toggleClass("slideLeft");
});

When changed that so it only loaded once it worked without .unbind()

Upvotes: 2

Related Questions