Pages

Sunday, December 13, 2015

Difference between $(document).ready & $(window).load JQuery events





Understand with an example: Calculate Image height & width and display on web page.

     1.     First write code in $(document).ready() event

<script type="text/javascript">
    $(document).ready(function () {
        $('#imageheightwidth').html(
            "Image height: " + $('#imgdesert').height() + " <br/> Image width: " + $('#imgdesert').width()
            );
    });
</script>
<body>
    <label id="imageheightwidth"></label><br />
    <img id="imgdesert" src="Desert.jpg" />
</body>

Output:
Image height: 0
Image width: 0

You got the height & width zero because $(document).ready(function () fires before images fully loaded and find no image.

2. Secondly write the same code in $(window).load() event

  <script type="text/javascript">
    $(window).load(function () {
        $('#imageheightwidth').html(
            "Image height: " + $('#imgdesert').height() + " <br/> Image width: " + $('#imgdesert').width()
            );
    });
</script>


Output:
Image height: 768
Image width: 1024


Now you got the correctly calculated height and width because $(window).load(function () fires after images fully loaded and found the image when calculated.



No comments:

Post a Comment