Jake
Jake

Reputation: 31

Why won't this super simple jQuery work?

<style type="text/css">
    #box { background: red; width: 100px; height: 100px; color: #fff; line-height: 100px; }
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
    $(function() {

        $('a#clickMe').click(function(e) {
            e.preventDefault();
            $('#box').css('position', 'absolute').animate({
                'left' : '+=100px'
            }, function() {

                    if ($('#box').offset().left > $(document).width()) {
                        alert('that is far enough')
                    }

            });

        });
    });
</script>

<a href="" id="clickMe">Click Me</a>

<div id="box">I Move!</div>

I'm trying to alert "that is far enough" when the box reaches the end of the page. But the alert never shows.

EDIT

Never mind, figured it out. I had to use $(window).width() instead of $(document).width();

Upvotes: 1

Views: 204

Answers (2)

Daniel Baulig
Daniel Baulig

Reputation: 10989

You have 2 problems:

  1. offset().left is (probably) not what you are looking for, but offset().left + width of the element.
  2. If the element moves off the right edge of the document, the document will increase in width and so you can never be off the far edge.

Have a look at this example. This is one option to solve this problem. The other is to save the documents width property somewhere and keep comparing to the original width, before the div element "stretches" the document element.

Upvotes: 1

user113716
user113716

Reputation: 322492

Because moving the element to the left is expanding the width of the document.

Try adding this css:

#wrapper {
    width:100%;
    height:100%;
    overflow:hidden;
    position:relative;
    margin:0;
    padding:0;
}
#box{ 
    background:orange;
    top:0;left:0;
}

<div id="wrapper">
    <a href="" id="clickMe">Click Me</a>

    <div id="box">I Move!</div>
</div>

Example: http://jsfiddle.net/UhgM5/1/


EDIT: Updated to make it FF compatible. Thanks to @Tomalak Geret'kal.

Upvotes: 1

Related Questions