Tutorial :jquery css class problem



Question:

There are 2 classes for the same

tag. class .bt1 set as default in html code.

I need this p tag to change its class on click and save it, and when I click on this p tag I need it to be 'bt1i' class and 'bt1i' onclick function start working. Can someone help me to understand why it do not work and where is the error. As I understand when I change the class in jquery code, it do not save for next call of jquery.

jQuery(document).ready(function(){      $(".slide1").animate({marginRight:"-446px"}, 500 );    $(".commonslide").animate({width:"206px", opacity:0}, 400 );    $(".mainarea").animate({marginRight:"206px"}, 500);         $(".bt1").click(function(){        $(this).toggleClass("bt1i");    $(".mainarea").animate({marginRight:"652px"}, 400);    $(".sidebar").animate({marginRight:"0px"}, 400 );          $(".slide1").animate({marginRight:"0px"}, 400 );    $(".commonside").animate({width:"652px", opacity:1}, 400 );   });           $(".bt1i").click(function(){    $(".slide1").animate({marginRight:"-446px"}, 500 );      $(".commonside").animate({width:"206px", opacity:1}, 400 );    $(".mainarea").animate({marginRight:"206px"}, 500);       $(this).toggleClass("bt1");     });      });  


Solution:1

You need to change the .bt1i handler to work via .live(), like this:

$(".bt1").live('click', function(){   //and...  $(".bt1i").live('click', function(){  

When you do $(".bt1i").click(...) it's looking for elements with a class of bt1i at that time and binding a click handler to them...the elements you're toggling the class on didn't have the class then. With .live() it'll listen or elements with that class, no matter when they were added...the selector is evaluated at the time the event occurs.

As a side note if you want this to behave as expected, you need to toggle off the previous class as well, just add both to each .toggleClass() call, like this:

$(this).toggleClass("bt1 bt1i");  

This will effectively swap the class on the element.


Solution:2

Nick's answer is correct. Here is just another solution:

$(".bt1").click(function () {      if ($(this).hasClass("bt1i")) {          // add behavior for the bt1i class here      }      $(this).toggleClass("bt1i");  }  

The reason you are having the problem is because jQuery's .click() function binds the handler only to the items that currently have the bt1i class. Since the class will not be added until later, the handler doesn't get bound to anything.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »