Examples of JavaScript Events

0

All Contributions

Handling the resize event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JavaScript Handling the Resize Event</title>
</head>
<body>
    <p id="result"></p>
    <script>
        function displayWindowSize(){
            var w = window.outerWidth;
            var h = window.outerHeight;
            var txt = "Window size: width=" + w + ", height=" + h;
            document.getElementById("result").innerHTML = txt;
        }
        window.onresize = displayWindowSize;
    </script>
    <p><strong>Note:</strong> Resize the browser window to see how the resize event works.</p>
</body>
</html>

Output :

Window size: width=360, height=671

 

Note: Resize the browser window to see how the resize event work s.

Handling the unload event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JavaScript Handling the Unload Event</title>
</head>
<body onunload="alert('Are you sure you want to leave this page?');">
    <h1>This is a heading</h1>
    <p>This is paragraph of text.</p>
    <p><strong>Note:</strong> This example may not work. The unload event is not supported properly in most of the browsers.</p>
</body>
</html>

Output :

This is a heading

This is paragraph of text.

 

Note: This example may not work. The unload event is not supported properly in most of the browse rs.

Handling the load event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JavaScript Handling the Load Event</title>
</head>
<body onload="window.alert('Page is loaded successfully!');">
    <h1>This is a heading</h1>
    <p>This is paragraph of text.</p>
</body>
</html>

Output :

This is a heading

This is paragraph of text .

Handling the submit event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JavaScript Handling the Submit Event</title>
</head>
<body>
    <form action="/examples/html/action.php" method="post" onsubmit="alert('Form data will be submitted to the server!');">
        <label>First Name:</label>
        <input type="text" name="first-name" required>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Handling the change event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JavaScript Handling the Change Event</title>
</head>
<body>
    <select onchange="alert('You have changed the selection!');">
        <option>Select</option>
        <option>Male</option>
        <option>Female</option>
    </select>
	<p><strong>Note:</strong> Select any option in select box to see how it works.</p>
</body>
</html>

total contributions (16)

This topic belongs to these lists

need a help?


find thousands of online teachers now

New to examplegeek.com?

Join us