0

I have a button and it is generated dynamically. Initially it has the class "active" when u click on it class changes to "inactive". When u click again it should change to active.

So I have assigned click events using follwoing code.

$(".active").on("click",function(){
$(this).removeClass('active').addClass('inactive');
});

$(".inactive").on("click",function(){
$(this).removeClass('inactive').addClass('active');
});

Issue is every time first function get called. When I use live instead of on it works fine. How can i fix this.

xdazz
  • 158,678
  • 38
  • 247
  • 274
Rakhitha Nimesh
  • 1,393
  • 2
  • 16
  • 26

3 Answers3

1

You can't simply change .live to .on,

$(selector).live(event_type, function(){});

is same as

$(document).on(event_type, selector, function(){});

$("body").on("click", '.active', function(){
  $(this).removeClass('active').addClass('inactive');
});

$("body").on("click", '.inactive', function(){
  $(this).removeClass('inactive').addClass('active');
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

One option, that would need a minor change to the HTML would be this:

$(function(){    
    $(".toggle").on("click", function(){
        $(this).toggleClass("active").toggleClass("inactive");
    });    
});

​ This will affect all elements with a toggle class assigned to them, and assumes that it will initially have either inactive or active.

Matt Sieker
  • 9,349
  • 2
  • 25
  • 43
0

try jquery's toggleClass method.

I wrote a demo here that demonstrates two ways of achieving the same thing for links. You could do the same for buttons.

Prasanth
  • 5,230
  • 2
  • 29
  • 61