Joshua Joshua - 3 months ago 6
Javascript Question

JQuery animation moves on first click but not second

In this code I am trying to make the word "About" and eventually the work "Portfolio" move all the way to the left, and then all the way back when the x button that I added in is clicked, or when the word is clicked a second time. I got the animation of moving the word all the way to the left but I can not get the animation where it moves back to work, either when the button is clicked, or when the word is. Any help would be appreciated. Thank you!
(Sorry for the long links, not able to put shortened ones in posts)

https://jsfiddle.net/ngtef82y/



<div id='bckDrp'>
<div id='nav'>
<img src='https://cdn2.iconfinder.com/data/icons/media-and-navigation-buttons-round/512/Button_12-128.png' id='xBttn'>
<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 abtBack = function() {
if ($('#abt').css('right') == 210) {
$(this).animate({
left: 210
}, 450);
}
}

var main = function() {
//When any tab is clicked
$('#hme, #abt, #prt').click(function() {
$('#xBttn').toggle(300);
$('#xBttn').click(function() {
$('#xBttn').fadeOut(300);
$('#hme, #abt, #prt').animate({
opacity: 1
}, 300);
})
})

//When Home tab is clicked
$('#hme').click(function() {
if ($('#abt, #prt').css('opacity') == 0) {
$('#abt, #prt').animate({
opacity: 1
}, 300);
} else {
$('#abt, #prt').animate({
opacity: 0
}, 300);
}
});

//When About tab is clicked
$('#abt').click(function() {
if ($('#hme, #prt').css('opacity') == 0) {
$('#hme, #prt').animate({
opacity: 1
}, 300);
} else {
$('#hme, #prt').animate({
opacity: 0
}, 300);
}
if ($('#abt').css('right') == 210) {
$(this).animate({
left: 210
}, 450);
} else {
$(this).animate({
right: 210
}, 450);
}
});
}

$(document).ready(main);


I decided to leave the css out, check jsfiddle for full code.

Answer

My proposal is:

  • save the left position of your about element before attaching the event
  • inside the event handler check the left position against the saved one
  • change the animation so that you go left in back or forward direction
var abtLeft = $('#abt').offset().left;
//When About tab is clicked
$('#abt').click(function() {
  if ($('#hme, #prt').css('opacity') == 0) {
    $('#hme, #prt').animate({
      opacity: 1
    }, 300);
  } else {
    $('#hme, #prt').animate({
      opacity: 0
    }, 300);
  }

  if ($('#abt').offset().left == (abtLeft - 210)) {
    $(this).animate({
      left: "+=210"
    }, 450);
  } else {
    $(this).animate({
      left: "-=210"
    }, 450);
  }
});
}

Your updated fiddle