Search code examples
javascriptjqueryclassbuttonchain

button chain remove previous class


I'm working on a code to change body background img. It works with buttons where I click on a button and change the img. When I click on first button it works, then I click on second button and also it works...but when I click again on first button it doesn't work.

I tried some code to remove the previous class but it doesn't work. I don't really too much about code :'(

Thanks. Here is the code:

<script type="text/javascript">
        $(document).ready(function(){  

        $('.button1').click(function(){
            $('body').addClass('fondonieve1').siblings().removeClass('active'); 
         });
          $('.button2').click(function(){
            $('body').addClass('fondonieve2').siblings().removeClass('active');
          });
          $('.button3').click(function(){
             $('body').addClass('fondootono1').siblings().removeClass('active');

        });
       });
</script>

Solution

  • you can removeClass again like this

    $('body').addClass('fondonieve1').siblings().removeClass('active').removeClass('fondonieve2');
    

    so you code should be like this

    <script type="text/javascript">
            $(document).ready(function(){  
    
            $('.button1').click(function(){
                $('body').addClass('fondonieve1').siblings().removeClass('active').removeClass('fondonieve2');
             });
              $('.button2').click(function(){
                $('body').addClass('fondonieve2').siblings().removeClass('active').removeClass('fondonieve1');
              });
              $('.button3').click(function(){
                 $('body').addClass('fondootono1').siblings().removeClass('active').removeClass('fondonieve2');
    
            });
           });
    </script>