jQuery click toggle animation

I'm trying to learn how to use jQuery, and I've stumbled upon a problem. First off, I will show you the part of the code that causes the problem.

HTML

<div id="nav">
<div id="button"><p class="scroll" onclick="location.href='#ed';">Education</p></div>
<div id="button"><p class="scroll" onclick="location.href='#wxp';">Work Experience</p></div>
<div id="button"><p class="scroll" onclick="location.href='#oact';">Other Activities</p></div>
<div id="button"><p class="scroll" onclick="window.open('cv.pdf','mywindow');">View as PDF</p></div>
<div id="arrow_container"><div class="arrow" id="down"></div></div>

jQuery

$(document).ready(function(){
$("#arrow_container").toggle(
  function () {
    $("#nav").animate({marginTop:"0px"}, 200);
      }, function () {
    $("#nav").animate({marginTop:"-100px"}, 200);
  });
});

I want the div #nav, which is initially positioned partially outside of the screen, to move down when div #arrow_container is clicked. Then when #arrow_container is clicked again I want #nav to move up, to its original position.

At the moment, non of this happens. Can you tell me what the problem is and how I can fix it?

EDIT: a jsfiddle with the code, including some css

EDIT 2: The problem seems to be solved. Also thanks to someone whose username I forgot and answer has been deleted, but he had some great tips! Thank you!

Upvotes: 8

Views: 41453

Answers (2)

tsuensiu
tsuensiu

Reputation: 186

Try this:

$("#arrow_container").click( function(event){
    event.preventDefault();
    if ( $(this).hasClass("isDown") ) {
        $("#nav").stop().animate({marginTop:"-100px"}, 200);                            
    } else {
        $("#nav").stop().animate({marginTop:"0px"}, 200);
    }
    $(this).toggleClass("isDown");
    return false;
});

http://jsfiddle.net/us6sohyg/5/

Upvotes: 15

Timotheus0106
Timotheus0106

Reputation: 1586

for me that didn't work to 100% i had to edit a stop() event before every animate. so:

$("#arrow_container").click( function(event){
event.preventDefault();
if ($(this).hasClass("isDown") ) {
    $("#nav").stop().animate({marginTop:"0px"}, 200);          
    $(this).removeClass("isDown");
} else {
    $("#nav").stop().animate({marginTop:"-100px"}, 200);   
    $(this).addClass("isDown");
}
return false;
});

Upvotes: 4

Related Questions