stansyfert
stansyfert

Reputation: 1

if statement gets stuck at else

I'm trying to get a menu appear and disappear by clicking on the same word. I just started learning these languages. But I think I'm making some progress. After reading a lot on here and other sources online I figured out this:

var main = function() {

if($('.menu').css('top') == '-65px') {    
    $('.icon-menu').click(function() {
        $('.menu').animate({top: '10px'}, 400);
        $('.content').animate({top: '10px'}, 400);
    });
}

else {
    $('.icon-menu').click(function() {
        $('.menu').animate({top: '-65px'}, 400);
        $('.content').animate({top: '-65px'}, 400);
    });
}  
};

$(document).ready(main);

So far I'm able to make the menu appear but not disappear.

Who can help me?

Upvotes: 0

Views: 108

Answers (2)

Guffa
Guffa

Reputation: 700322

You are checking the position of the menu at the time of binding event, so there will always be one or the other event handler that will be bound, and it won't change when the event is handled.

Use one event handler instead, and check the position when the event happens:

$('.icon-menu').click(function() {
  if($('.menu').css('top') == '-65px') {    
    $('.menu').animate({top: '10px'}, 400);
    $('.content').animate({top: '10px'}, 400);
  } else {
    $('.menu').animate({top: '-65px'}, 400);
    $('.content').animate({top: '-65px'}, 400);
  }
});

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

You're checking the status of the menu only once, not on each click. Turn things inside out:

var main = function() {
  $('.icon-menu').click(function() {

    if ($('.menu').css('top') == '-65px') {    
      $('.menu').animate({top: '10px'}, 400);
      $('.content').animate({top: '10px'}, 400);
    } 
    else {
      $('.menu').animate({top: '-65px'}, 400);
      $('.content').animate({top: '-65px'}, 400);
    }
  });
};

Upvotes: 5

Related Questions