zazvorniki
zazvorniki

Reputation: 3602

Changing an icon inside a toggle button?

I have a button that has an icon in it, and I have some jQuery code opening and closing a div.

I have some code that switches the icon from a plus to minus, but the issue is that I have to click directly on the icon for it to work instead being able to click anywhere on the button, and that can be an issue for the minus icon.

My HTML looks like this:

<button class="pull-right toggleBtn span1"><i class="icon-plus"></i></button>

and my jQuery to switch the icons looks like this:

$(".toggleBtn").on('click','.icon-minus, .icon-plus',function(){
        $(this).toggleClass("icon-minus icon-plus");
    });

Any help would be awesome!

Upvotes: 0

Views: 13587

Answers (3)

Joshua Dwire
Joshua Dwire

Reputation: 5443

Change your JavaScript code to this:

$(".toggleBtn").on('click',function(){
    $(this).children('.icon-minus, .icon-plus').toggleClass("icon-minus icon-plus");
});

Your current code only listens to the click event on the icon. This code will listen to the click event on the entire button but still change the class only on the icon.

JSFiddle: http://jsfiddle.net/jdwire/B4avV/

Upvotes: 7

Kiran
Kiran

Reputation: 20313

Try:

$(document).on('click','.toggleBtn',function(){
        if ($(this).children().is('.icon-plus')) {
          $(this).children().removeClass('icon-plus');
      }else{
          $(this).children().addClass('icon-plus');
      }
});

Upvotes: 0

Bala
Bala

Reputation: 510

try this

$(document).on('click','.toggleBtn',function(){
    $(this).children().toggleClass("icon-minus icon-plus");
});

Upvotes: 1

Related Questions