Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.removeClass() after .addClass() not working

I have two class empty and colored. Once I clicked colored class then remove colored class and add empty class. Again I click on it it should be add colored class and remoce empty class. But it is't working.

            var color_click = false;
            var select_color = "";
            $( ".colored").on('click',function(e){
                if(color_click != true){
                    color_click = true;
                    select_color = $(this).css('background-color');
                    $(this).removeClass("colored");
                    $(this).addClass( "empty");
                    $(this).css('background-color','')
                }
            });


            $( ".empty").click(function(){
                if(color_click == true){
                    color_click = false;
                    $(this).css('background-color',select_color);
                    $(this).addClass("colored");
                    $(this).removeClass( "empty");

                }
            });
like image 946
Mangala Edirisinghe Avatar asked Aug 03 '26 12:08

Mangala Edirisinghe


1 Answers

Yes. That is because you bind the event to that particular class. You can use event delegation to resolve the issue using on(). When your event binding happens there is no element with the class .empty and the binding has no effect. Instead of using the document head(as used in my example) use a container that exists in DOM all the time and holds this element. So with event delegation you are actually binding the event to a container/document head for delegation on the elements that are present in DOM now as well as for the future.

Apart from this i have made some changes to remove some ambiguous check and use chaining.

   $(document).on('click', ".colored", function(e){
            if(!color_click){ // You dont need this check if your variable is modified only in these 2 events
                color_click = true;
                select_color = $(this).css('background-color');
                $(this).removeClass("colored").addClass( "empty").css('background-color','');

            }
        });


        $( document).on('click', ".empty", function(){
            if(color_click){// You dont need this check if your variable is modified only in these 2 events
                color_click = false;
                $(this).addClass("colored").removeClass("empty").css('background-color',select_color);

            }
        });
like image 99
PSL Avatar answered Aug 06 '26 02:08

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!