worksAsIntended
worksAsIntended

Reputation: 37

JS/JQuery change class and SlideDown/Up

I have a page with a top menu that changes into a minimized version when the user scrolls down. I'm doing this by changing the class of the element, so the CSS changes its appearance.

I would like to perform a simple slideDown/slideUp, as the minimized menu bar appears/disappears, at the same time, but just adding the animation to my current code doesn't work as I hoped it would.

Here's the code snippet I'm using to minimize the menu:

$(window).scroll(function () {
    if ($(document).scrollTop() < topMenuHeight) {
        $("nav").removeClass("min");      
    } else {
        $("nav").addClass("min");
    } 
});

topMenuHeight refers to the menu's height (obviously) and was set as a variable previously on the code.

How can I make this work? I had tried setting a variable to check if the menu was minimized or not, but it didn't seem to work.

Any help is appreciated. Although, I know there are some animation plugins out there, but for this project I want to keep it lean.

Thank you for your time!

Upvotes: 1

Views: 1898

Answers (2)

Trevor
Trevor

Reputation: 16116

Well here is an example with slideUp and slideDown

CSS

nav {
    height: 200px;
    background: lightblue;
    margin-bottom: 50px;
    margin-top: -16px;
}
nav.min {
    position: fixed;
    height: 80px;
    background: red;
}

JQuery

$(window).scroll(function () {
    if($(this).scrollTop() != 0  && !$("nav").hasClass("min"))
    {
       $("nav").slideUp(function(){
           $("nav").addClass("min");
           $("nav").slideDown();
       });
    }
    else if($(this).scrollTop() == 0 && $("nav").hasClass("min"))
    {
        $("nav").slideUp(function(){
            $("nav").removeClass("min");
            $("nav").slideDown();
        });    
     }
});

FIDDLE

http://jsfiddle.net/VD6wf/22/

Upvotes: 1

worksAsIntended
worksAsIntended

Reputation: 37

This (adding a stop) seems to have solved the glitch:

$(window).scroll(function () {
  if ($(document).scrollTop() < topMenuHeight+100) {
    $("nav").stop().animate({ 
     top: "-4em"
     }, 200, function() {
      $("nav").removeClass("min"); 
     });      
  } else {
    $("nav").addClass("min");
    $("nav").stop().animate({ 
     top: 0
    }, 200 );
  } 
 });
});

Upvotes: 0

Related Questions