Prateek
Prateek

Reputation: 1

What is the difference between writing $(window).scroll(); inside document.ready() and outside it?

What is the difference between the below two codes?

1.

$j(document).ready(function() {
    $j(window).scroll(function() {
        // do something
    });
});

2.

$j(window).scroll(function() {
    // do something
});

Upvotes: 0

Views: 1738

Answers (2)

Julien Ambos
Julien Ambos

Reputation: 2098

The code

$j(document).ready(function() {
    $j(window).scroll(function() {
        // do something
    });
});

only executes when the DOM has loaded, in contrast to

$j(window).scroll(function() {
   // do something
});

which executes as soon as the javascript execution reaches this part of code

Read for further information: https://api.jquery.com/ready/.

Upvotes: 2

broodjetom
broodjetom

Reputation: 286

$(document).ready(function(){ }); only runs when everything is loaded, this means including images and iframes. So when you scroll you actually scroll to the point that you want to go to. In case the images are not loaded yet, you will scroll to a part, and then the images load which makes the page change and move element, which then can be add a different place then where you initially scrolled to.

https://learn.jquery.com/using-jquery-core/document-ready/

Upvotes: 0

Related Questions