CBSE 22. WEB SCRIPTING - JAVA SCRIPT (5 MARKS)

 

30. Execute JavaScript When a Button is Clicked

  • Using the onclick Event:
    • Add the onclick attribute to the <button> tag.
    • Assign the JavaScript code or the name of a function to this attribute.

HTML

<!DOCTYPE html>

<html>

<head>

    <title>Button Click Example</title>

</head>

<body>

 

    <button onclick="alert('Button clicked!');">Click Me</button>

 

    <script>

        function myButtonClick() {

            alert("Button clicked using a function!");

        }

    </script>

 

    <button onclick="myButtonClick()">Click Me (Function)</button>

 

</body>

</html>

Visual Representation:

[Image of HTML code with <script> tag and onload event] [Image of HTML code with <button> tag and onclick event]

Key Points for Students:

  • Event Handling: These examples demonstrate event handling, a crucial concept in JavaScript. Events are actions that occur on a web page, such as page loading or button clicks.
  • Event Listeners: The onload and onclick attributes are examples of event listeners. They "listen" for the specified event to occur and then execute the associated code.
  • Functions: Using functions (like myFunction() and myButtonClick()) helps organize your code and make it reusable.

No comments:

Post a Comment