Joshua Joshua - 3 months ago 10
HTML Question

How to toggle an animation in Jquery

I am trying to make an animation on a navigation menu where when an option is clicked the other two fade out, since .fadeToggle had problems with positioning for me I decided to just animate the opacity to 0, and then back to 1 when clicked on again. (I left the CSS out the the code posted down below)

https://jsfiddle.net/L703yvke/

<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>





var main = function(){
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 0},300 );
});
if($('#abt, #prt').css('opacity') == 0) {
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 1},300 );
}
)};
}

$(document).ready(main);

Answer

The main function only runs once. So you are only doing that if-statement once. Also you are binding click events, which I don't think is what you are expecting it to do. Instead you can simply use a if-else and have your condition inside the click event:

var main = function(){
  $('#hme').click(function(){
    if($('#abt, #prt').css('opacity') == 0) 
        $('#abt, #prt').animate({opacity: 1},300 );
    else
        $('#abt, #prt').animate({opacity: 0},300 );
  });
}

Demo

Comments