Bootstrap - switch icon with jquery

I am having a slight problem trying to toggle the Bootstrap icon. When I run the code, it does what is expected the first time I click on the icon, which it switches, but when I click again, it does not change. Here is my code and any help would be appreciated!

<a><i class="icon-plus"></i></a> <script> $(".icon-minus").click(function(){ $(this).removeClass("icon-minus").addClass("icon-plus"); }); $(".icon-plus").click(function(){ $(this).removeClass("icon-plus").addClass("icon-minus"); }); </script> 

Update 1:

This icon is for a folding menu, and the code for this can be found here :)

+6
source share
3 answers

jsBin demo

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

Or this if you dynamically create your elements:

 $("#parent_el_NOT_dyn_gen").on('click','.icon-minus, .icon-plus',function(){ $(this).toggleClass("icon-minus icon-plus"); }); 
+14
source

The jQuery selector selects the DOM elements, then applies a click handler to them. It does not overestimate the selector after changing classes in the element.

You probably want delegate() / on() from jQuery to dynamically change the handler that starts when an element is clicked. The delegate works with event bubbles and handles the click and evaluates whether the source of the click matches the selector (during the click), and not to .click() , which attaches the handler directly, once (during the loading page or whenever the code was executed )

Another solution is to change the handler, either by evaluating which class is in the existing element, or using toggleClass() , which will check the class and then invert it.

 $(".icon-minus, .icon-plus").click(function() { var $this = $(this); if ($this.hasClass("icon-plus")) { $this.removeClass("icon-plus").addClass("icon-minus"); return; } if ($this.hasClass("icon-minus")) { $this.removeClass("icon-minus").addClass("icon-plus"); return; } }); 

This method will be a little faster than using on() / delegate() , because it is processed in the root handler and not sparged and checked later. It is also not subject to any interruption in the bladder. (i.e. event.stopPropagation() )

+1
source

A simple solution for Bootstrap 3.

 $('[data-toggle="collapse"]').click(function(e) { $(e.target).find('.icon-minus-sign, .icon-plus-sign').toggleClass("icon-minus-sign icon-plus-sign"); }); 
0
source

Source: https://habr.com/ru/post/920613/


All Articles