Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass & removeClass not working

I have a menu, it should work as a click menu, so when clicking the button a menu will appear, and when clicking the button again, the menu should disapear, but i cant get it to work ?

I've got this script

<script type="text/javascript">
      $(document).ready(function() { 
        $('#dropdown').click(function(){
            setTimeout(function(){
                $('#dropdown').attr("id", "dropdown2");
                $('#dropmenu').addClass("open");
                //$('#dropmenu').fadeIn('fast');
            },500);
        })
        $('#dropdown2').click(function(){
            setTimeout(function(){
                $('#dropdown').attr("id", "dropdown");
                $('#dropmenu').removeClass("open");
                //$('#dropmenu').fadeIn('fast');
            },500);
        })
      });
    </script>

It works fint when adding the class, but then when im clicking the button again, it wont remove the class "open"


2 Answers

After you write $('#dropdown').attr("id", "dropdown2");, there is no #dropdown element for the code in the second handler to match.
Also, when you bind the second handler, there is no #dropdown2 element yet. (live events would solve that issue)

Instead, you should use the toggle event, which allows you to bind multiple click handlers that will execute every other click.

For example:

$(document).ready(function() { 
    $('#dropdown').toggle(
        function() {
            setTimeout(function(){
                $('#dropdown').addClass("open")
                              .fadeIn('fast');
            }, 500);
        },
        function() {
            setTimeout(function(){
                $('#dropdown').removeClass("open")
                              .fadeOut('fast');
            }, 500);
        }
    );
});
like image 66
SLaks Avatar answered Dec 02 '25 13:12

SLaks


The reason it isn't working is that the dropdown2 id doesn't exit when you register the click handler. You could use to live to overcome this, but it is better to use classes:

  $(document).ready(function() { 
    $('#dropdown').click(function(){
        if (!$(this).hasClass("open")) {
          setTimeout(function(){
              $('#dropmenu').addClass("open");
             //$('#dropmenu').fadeIn('fast');
          },500);
       } else {
        setTimeout(function(){
            $('#dropmenu').removeClass("open");
            //$('#dropmenu').fadeIn('fast');
        },500);
      }
    })
  });
like image 27
kgiannakakis Avatar answered Dec 02 '25 14:12

kgiannakakis



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!