1

I have the following script.

<script type="text/javascript">
    $(function () { // document ready
        var contentTop = $('.share').offset().top; // returns number 
        $(window).scroll(function () { // scroll event             
            var wayPoint = $(window).scrollTop(); // returns number               
            if (contentTop < wayPoint) {
                var shareWidth = $('.content').width();
                $('.share-active').width(shareWidth);
                $('.share').replaceWith('<div class="share-active">SOCIAL BUTTONS</div>');
            } else {
                $('.share-active').replaceWith('<div class="share"></div>');
            }
        });
    });
</script>

DEMO : http://jsfiddle.net/franciscop/b39M4/3/

Somehow the share-activediv is appearing before the scroll top reaches share div. I don't know what I am going wrong.

Also, anyway to animate the apperance of the share-active div so users are attracted to it.

Can you help me find where the problem is?

1 Answer 1

2

I believe you are getting the offset of your element too quickly. When document.ready fires the image(s) probably hasn't fully loaded. So you can either give the images on your page specific height values so they take-up the required space before they actually load, or you can use the window.load event to get your offset.

The easiest fix would probably be changing:

$(function () { // document ready

to:

$(window).on("load", function () { // window load

Here is a demo: http://jsfiddle.net/b39M4/4/

This has the side-effect that your code won't work until the whole page has loaded. So another method would be to update the contentTop variable whenever necessary. Once on document.ready, once on window.load and maybe once each time an image loads. This would make it so the code would initialize faster and more accurately reflect the reality of the webpage's layout.

To animate the appearance of the element you can give it an initial opacity of zero and then after adding the element to the DOM, selecting it and animating it into visibility.

Also, you really should throttle the window.scroll event handler because some browsers will just lockup since there are so many window.scroll events that fire when using the scroll bar.

Sign up to request clarification or add additional context in comments.

3 Comments

Its taking too long for all elements of page to get loaded... Anyway to call the funtion after the main image load itself...
@DebajyotiDas You can bind to the image.load event for the <img /> element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.