views:

26

answers:

1

Hello all, I have a div which I place at the top right-hand corner of a website, absolutely positioned at top: 0px and right : 0px. I want to use jquery's animate function to animate the div left or right a certain amount when a button is clicked, but stop the animation if at anytime, the div's offset to the left or right is less than a certain number. I want to do this to accomodate users who click the left or right buttons more than once, so that the div does not fly out of sight. How does one accomplish this? Below is my relevant css, html, and jquery code:

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="some/link">some text</a></span>
            <br />
            <span id = "scoreHolder">some text</span>
            <br />
            <button type="button" id="moveLeft">Left</button>&nbsp;<button type="button" id="moveRight">Right</button>
        </div>

jQuery (at the moment):

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

    $("#moveLeft").bind("click", function() {
            $("#scorecardTwo").animate({"right":"+=76%"}, "slow");
                            // how to stop animation if offset is less than appropriate number?
    });

    $("#moveRight").bind("click", function() {
            $("#scorecardTwo").animate({"right" : "-=76%"}, "slow");
                            // how to stop animation if offset is less than appropriate number?
    }); 
+1  A: 

One way is to remove the event listener on the buttons when clicked once, so the user can't click again:

$("#moveLeft").bind("click", function() {
    $("#scorecardTwo").animate({"right":"+=76%"}, "slow");
    $(this).unbind('click', arguments.callee);
});

Another way would be to check the location on each step:

$("#moveLeft").bind("click", function() {
    $("#scorecardTwo").animate({"right":"+=76%"}, {
        speed: "slow",
        step: function(right) {
            if (right >= 70) { // stop at ~70
                $("#scorecardTwo").stop();
            }
        }
    });
});
David