Handling HTML Events using JavaScript

HTML events are actions or occurrences that happen on a webpage, such as a button click, mouse movement, or keyboard input. JavaScript allows you to respond to these events and perform actions accordingly. Here's a step-by-step tutorial:

1. Basic Event Handling:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Handling HTML Events</title>
</head>
<body>
    <button id="myButton">Click me</button>

    <script>
        // Accessing an element by its ID
        var buttonElement = document.getElementById('myButton');

        // Adding a click event listener
        buttonElement.addEventListener('click', function() {
            alert('Button clicked!');
        });
    </script>
</body>
</html>

2. Mouse Events:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse Events</title>
</head>
<body>
    <div id="myDiv">Hover over me</div>

    <script>
        // Accessing an element by its ID
        var divElement = document.getElementById('myDiv');

        // Adding a mouseover event listener
        divElement.addEventListener('mouseover', function() {
            alert('Mouse over the div!');
        });

        // Adding a mouseout event listener
        divElement.addEventListener('mouseout', function() {
            alert('Mouse out of the div!');
        });
    </script>
</body>
</html>

3. Keyboard Events:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keyboard Events</title>
</head>
<body>
    <input type="text" id="myInput" placeholder="Type here">

    <script>
        // Accessing an element by its ID
        var inputElement = document.getElementById('myInput');

        // Adding a keyup event listener
        inputElement.addEventListener('keyup', function(event) {
            alert('Key pressed: ' + event.key);
        });
    </script>
</body>
</html>

These examples showcase the basics of handling HTML events using JavaScript. As you explore further, you can discover additional event types and create interactive and responsive web applications by responding to user actions on your web page.