2081 5

CSC329 ยท 2081 ยท 5 marks

What is onload event in HTML? Write an HTML script that displays alert message 'Hello Nepal' in onload event.

What is onload event in HTML? Write an HTML script that displays alert message 'Hello Nepal' in onload event. [5]

Web TechnologyChapter 2: Hyper Text Markup LanguageHTML Events

Quick answer

The onload event is an event handler in HTML/JavaScript that is triggered automatically when a web page (or an element such as an image) has completely finished loading in the browser. It is commonly used with the <body> tag.

Onload Event in HTML

Definition

  • It belongs to the category of Event Handlers -- JavaScript code placed inside HTML tags that execute when something happens.
  • The basic syntax of an event handler is:
name_of_handler = "JavaScript code goes here"

For the onload event specifically:

<body onload="JavaScript code or function call">

The onload event is useful for:

  • Displaying welcome messages when a page loads
  • Initializing variables or functions automatically
  • Checking cookies or browser information on page start

HTML Script: Display Alert 'Hello Nepal' on Onload Event

<html>
  <head>
    <title>Onload Event Example</title>
    <script type="text/javascript">
      function showMessage() {
        alert("Hello Nepal");
      }
    </script>
  </head>

  <body onload="showMessage()">
    <h2>Welcome to Nepal!</h2>
    <p>This page demonstrates the onload event in HTML.</p>
  </body>
</html>

Explanation of the Script

PartDescription
<script type="text/javascript">Defines the JavaScript block inside the <head> tag
function showMessage()A JavaScript function that triggers an alert box
alert("Hello Nepal")Displays a popup dialog with the message Hello Nepal
<body onload="showMessage()">Calls showMessage() automatically when the page finishes loading

How It Works

  1. The browser loads the HTML page completely.
  2. As soon as the <body> finishes loading, the onload event is fired.
  3. The showMessage() function is called automatically.
  4. An alert box appears with the message "Hello Nepal".
  5. The user clicks OK and sees the rest of the page content.

Note: The onload event handler follows the same event handling principle described in the curriculum: event handlers are placed inside HTML tags (not inside <script> tags) and execute JavaScript when a specific event occurs.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.