views:

46

answers:

1

Hello,

I seem to be having difficulties using jQuery .animate() to animate an absolutely positioned div from right to left on a button click, and left to right on another button click. I was wondering if you would be willing to help me understand what I'm doing wrong? Thanks. Below is my relevant CSS, HTML, and jQuery code. I can click the #moveLeft button and it wil indeed animate it to the left, but when I click the #moveRight button, nothing happens. Where am I going wrong?

Thanks!!

CSS

      #scorecardTwo {
       position:absolute;
       padding:5px;
       width: 300px;
       background-color:#E1E1E1;
       right:0px;
       top:0px;
       display:none;
        } 

HTML

<div id = "scorecardTwo"> 
   <span id = "dealHolder"><a href="link/to/stuff">text</a></span>
   <br />
   <span id = "scoreHolder">text</span>
   <br />
   <button type="button" id="moveLeft">Left</button>&nbsp;<button type="button" id="moveRight">Right</button>
 </div>

jQuery

$("#scorecardTwo").fadeIn("slow");

$("#moveLeft").bind("click", function() {

 var config = {
   "left" : function() { 
     return $(this).offset().left;
     },
    "right" : function() {
        return $("body").innerWidth() - $K("#scorecardTwo").width();
      }
  };

  $("#scorecardTwo").css(config).animate({"left": "0px"}, "slow");
  $(this).attr("disabled", "disabled");
  $("#moveRight").attr("disabled", "");
 });

 $("#moveRight").bind("click", function() {

   var config = {
     "left" : function() { 
       return $(this).offset().left;
      },
      "right" : function() {
       return $("body").innerWidth() - $K("#scorecardTwo").width();
      }
   };

   $("#scorecardTwo").css(config).animate({"right" : "0px"}, "slow");
   $(this).attr("disabled", "disabled");
   $("#moveLeft").attr("disabled", "");
 }); 
+2  A: 

When moving it right, you should set the CSS left to null.

Demo

$("#moveRight").click(function() {
    var config = {
        left: null,
        right: $("body").innerWidth() - $("#scorecardTwo").width()
    }

    $("#scorecardTwo").css(config).animate({right : "0px"}, "slow");
    $(this).attr("disabled", "disabled");
    $("#moveLeft").attr("disabled", "");
}); 
SLaks
this worked awesome! May I ask why we need to set `left` to null in order to animate it to the right?
Alex
Because `left` has priority over `right`.
SLaks
By the way, you don't need to use functions.
SLaks
Ah ok. I did not know that. Makes sense now. Thanks.
Alex
+1 Nice answer, even provided a demo, awesome...
moi_meme