-->

20 April 2021

Running code when a page is ready in jQuery

  Asp.Net CS By Example       20 April 2021
Running code when a page is ready in jQuery

 In this post we are learn about to running code when a page is ready in jQuery. jQuery lets we run our code when the page elements we want to work on have been loaded (better than the browser onload function, which is called only after all images have been loaded too).

 To run code when the page is ready, we use this syntax:

 $(document).ready(function() {    
   ...
 });

 There is a shorthand as well:

 $(function() {    
   ...
 });

 In this example, we will add a style class to a <p> element to color its background cyan when the page loads.

 Note that this script would not work unless we waited for the page to load, because the <p> element would not be available to our code sooner (the code runs when the <head> section is loaded, not the <body> section).

jqscript3.1.html
<html>
<head>
    <title>
        Running code when a page is
        ready
    </title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(function( ) {
            $("p.third")
            .addClass("striped");
        });
    </script>
    <style>
        p.third {
            font-weight: normal;
        }
        p.striped {
            background-color: cyan;
            width: 300px;
        }
    </style>
</head>
<body>
    <h1>
        Running code when a page is
        ready
    </h1>
    <div>
        <p>This is paragraph 1.</p>
        <p>This is paragraph 2.</p>
        <p class="third">
            This is paragraph 3.
        </p>
        <p>This is paragraph 4.</p>
    </div>
    
</body>
</html>


Output:

logoblog

Thanks for reading Running code when a page is ready in jQuery

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.