Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove css class on button click

Tags:

jquery

I'm using this code to show and hide sidebar in my html page

$(document).ready(function(){

       $('button.rside').click(function(){
               $( "#all-labels" ).removeClass( "side-click" );
               $( ".box" ).removeClass( "box-side" );
               $(this).removeClass( "rside" );
               $(this).addClass( "side" );
          });
       $('button.side').click(function(){
               $( "#all-labels" ).addClass( "side-click" );
               $( ".box" ).addClass( "box-side" );
                $(this).addClass( "rside" );
                $(this).removeClass( "side" );
          });
     });

This code working well when i click on the button, add new class and relace the button class side with rside, button the same code for the new button class rside for returning all elemnts to it's normal position not working.

like image 359
Mohamed Abo ElGhranek Avatar asked Jan 23 '26 14:01

Mohamed Abo ElGhranek


1 Answers

You need event delegation.use .on():

 $(document).on('click','button.rside',function(){
           $( "#all-labels" ).removeClass( "side-click" );
           $( ".box" ).removeClass( "box-side" );
           $(this).removeClass( "rside" );
           $(this).addClass( "side" );
      });
 $(document).on('click','button.side',function(){ 
           $( "#all-labels" ).addClass( "side-click" );
           $( ".box" ).addClass( "box-side" );
            $(this).addClass( "rside" );
            $(this).removeClass( "side" );
      });
like image 80
Milind Anantwar Avatar answered Jan 25 '26 04:01

Milind Anantwar