zelocalhost
zelocalhost

Reputation: 1183

addClass / removeClass not working

I have a problem for use this two jquery functions, so this is my fiddle : http://jsfiddle.net/Wv6gN/5/

and my js code :

$("a#slidingMenuButton.noState").click(function() {

$("i.fa-bars").addClass("textToLeft");
 $("a#slidingMenuButton").addClass("BtextToLeft").removeClass("noState");
    alert("lol1");

});


$("a#slidingMenuButton.BtextToLeft").click(function() {

   $("i.fa-bars").removeClass("textToLeft").addClass("textToRight");       $("a#slidingMenuButton").removeClass("BtextToLeft").addClass("noState");
  alert("lol2");

});

it's always the first onclick event that is made. why the addClass/removeClass not working ?

Upvotes: 0

Views: 5211

Answers (4)

james emanon
james emanon

Reputation: 11807

You need to bind the elements with either 'delegate' or 'on' in your usage. The reason being is that delegate or on will bind your elements NOW and IN THE FUTURE, as they exist and/are created. This is useful for elements that are updated alot or change classes etc...

http://api.jquery.com/on/

http://api.jquery.com/delegate/

When you set up your initial handlers those elements, in how you try to access them, do not exist.

So, you will need to change your code to: http://jsfiddle.net/Wv6gN/12/

update your code here: as others have noted. Use the ".on" method.

 $(document).on('click', 'a#slidingMenuButton.BtextToLeft', function () {

Upvotes: 1

user3047675
user3047675

Reputation: 82

Use toggleClass instead.

$("a#slidingMenuButton.noState").click(function() {
  $("i.fa-bars").addClass("textToLeft");
  $("a#slidingMenuButton").toggleClass("BtextToLeft").toggleClass("noState");
  alert("lol1");
});

toggleClass will remove the class if it's there and add it when it's not. Here's your updated fiddle.

Upvotes: 1

pathfinder
pathfinder

Reputation: 1776

I would put these together into one function

$("a#slidingMenuButton").click(function() {
    if($(this).hasClass('noState') {
      $("i.fa-bars").addClass("textToLeft");
      $("a#slidingMenuButton").addClass("BtextToLeft").removeClass("noState");
      alert("lol1");
 }
else {
    if($(this).hasClass('BtextToLeft') {
      $("i.fa-bars").removeClass("textToLeft").addClass("textToRight");           
      $("a#slidingMenuButton").removeClass("BtextToLeft").addClass("noState");
      alert("lol2");
     }
  }
});

Upvotes: 1

Kyle Needham
Kyle Needham

Reputation: 3389

You need to use .on so that you can bind to a dynamically created element. Demo

$(document).on('click', 'a#slidingMenuButton.BtextToLeft', function () {
    $("i.fa-bars").removeClass("textToLeft").addClass("textToRight");
    $("a#slidingMenuButton").removeClass("BtextToLeft").addClass("noState");
    alert("lol2");
});

Upvotes: 2

Related Questions