Open In App

HTML DOM onload Event

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The HTML DOM onload event in HTML occurs when an object has been loaded. The onload event is mostly used within the <body> tag, in order to run the script on the web page that will load all the content completely. The onload event can be used to check the user’s browser type and browser version and load the version of the web page based on the information. The onload event can also be used for cookies. 

In HTML:

<element onload="scriptFile">
HTML
<!DOCTYPE html>
<html>
<body>
 <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211113003851/geeks-300x83.png" 
      id="imgid" 
      alt="GFG_logo"
      onload="document.getElementById('pid').innerHTML = 'Image loaded';">
 <p id="pid"></p>
</body>
</html>

Using the addEventListener() method:

object.addEventListener("load", scriptFile);
HTML
<!DOCTYPE html>
<html>
<body>
    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20211113003851/geeks-300x83.png" 
         id="imgid" alt="GFG_logo">
    <p id="pid"></p>

    <script>
        document.getElementById("imgid")
        .addEventListener("load", GFGFun);
        function GFGFun() {
            document.getElementById("pid")
            .innerHTML = "Image loaded";
        }
    </script>
</body>
</html>

In JavaScript:

object.onload = function(){scriptFile};
HTML
<!DOCTYPE html>
<html>
<body>
    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211113003851/geeks-300x83.png" 
         id="imgid" alt="GFG_logo">
    <p id="pid"></p>
    <script>
        // Set the onload event for the image
        document.getElementById("imgid").onload = function () {
            document.getElementById("pid").innerHTML = "Image loaded";
        };
    </script>
</body>
</html>

Supported tags:

  • <body>: It is used to define the main content present inside an HTML page.
  • <frame>: It is used to divide the web browser window into multiple sections where each section can be loaded separately.
  • <iframe>: It is used to define a rectangular region within the document in which the browser can display a separate document, including scrollbars and borders.
  • <img>: It is used to add images inside a webpage/website.
  • <input type=”image”>: It is used to specify the type of <input> element to display.
  • <link>: It is used to define a link between a document and an external resource.
  • <script>: It is used to define the client-side script.
  • <style>: It is used to modify our text, viewed in the page.


Next Article

Similar Reads