BryanK
BryanK

Reputation: 1221

jQuery event triggers only fire once...I need them to always work

$(document).ready(function(){
  $('#nav').mouseup(function(){
        $(this).css('height','33em')
        .mouseup(function(){
              $(this).css('height','5.7em');      
        });      
  });
});

http://jsfiddle.net/bryank/afcnR/

I think I'm missing a basic concept here... I got my drop down menu to work using jQuery by but it only works once, then stops working. I need the mouseup events to go back to the beginning of the function some how?

Upvotes: 1

Views: 295

Answers (2)

FishBasketGordo
FishBasketGordo

Reputation: 23142

You have a case of competing event handlers, and the last one (the one that sets the height to 5.7em) wins. The event handlers actually stack, so you keep adding additional copies of the one that closes the menu.

Try maintaining the open/closed state independently. Something like this (jsfiddle):

$(document).ready(function () {
    $('#nav').data('open', 0).mouseup(function () {
        if ($(this).data('open') == 0) {
            $(this).css('height', '33em').data('open', 1);
        } else {
            $(this).css('height', '5.7em').data('open', 0);
        }
    });
});

Or better yet, move the CSS details to a CSS class:

#nav { height: 5.7em; }
.open { height: 33em !important; }

...and just toggle that class on and off (jsfiddle):

$(document).ready(function () {
    $('#nav').mouseup(function () {
        $(this).toggleClass('open');
    });
});

Upvotes: 4

carrabino
carrabino

Reputation: 1762

Use a class to flag the current state. This is a very useful technique that's used in many ways. In this case, i used a class called "selected", but you can use whatever you like.

This fiddle shows it working:
http://jsfiddle.net/acturbo/afcnR/1/

jquery:

   $(document).ready(function(){

        $('#nav').on("mouseup", function(){

           $(this).toggleClass("selected");

           if ( $(this).hasClass("selected") ){
                 $(this).css('height','33em');
           }else{
                  $(this).css('height','5.7em');      
           }


        });
    });

Upvotes: 2

Related Questions