Dular SharmaDular SharmaDular Sharma
(Monday - Saturday)
sharmadular7392@gmail.com
Himatnagar
Dular SharmaDular SharmaDular Sharma

Chapter 7. Events In JavaScript

62 Views

Events are an essential part of JavaScript, enabling developers to create interactive web pages by responding to user actions such as clicks, key presses, and mouse movements. Understanding how to handle events effectively is crucial for building dynamic and responsive web applications. In this blog, we’ll explore the basics of JavaScript events, how to handle them, and provide practical examples.

What are Events?

Events in JavaScript refer to actions or occurrences that happen in the browser, such as user interactions or changes in the document’s state. Common types of events include:

  • Mouse Events: click, dblclick, mouseover, mouseout, mousedown, mouseup
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, focus, blur, change
  • Window Events: load, resize, scroll, unload

Event Handling

Event handling involves writing code that executes in response to an event. There are several ways to handle events in JavaScript:

  1. Inline Event Handlers
  2. Event Handler Properties
  3. Event Listeners

Inline Event Handlers

Inline event handlers are defined directly in the HTML markup. While easy to implement, they are generally discouraged for maintainability and separation of concerns.

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

Event Handler Properties

Event handler properties allow you to assign a function to an event property of an element.

<!DOCTYPE html>
<html>
<head>
    <script>
        function showAlert() {
            alert('Button clicked!');
        }
    </script>
</head>
<body>
    <button id="myButton">Click Me</button>
    <script>
        document.getElementById('myButton').onclick = showAlert;
    </script>
</body>
</html>

Event Listeners

Event listeners provide a more flexible and powerful way to handle events. They allow you to add multiple handlers to a single event and remove them if needed.

<!DOCTYPE html>
<html>
<head>
    <script>
        function showAlert() {
            alert('Button clicked!');
        }

        document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById('myButton').addEventListener('click', showAlert);
        });
    </script>
</head>
<body>
    <button id="myButton">Click Me</button>
</body>
</html>

Event Object

When an event occurs, an event object is created, containing information about the event. This object is passed to the event handler, providing details such as the event type, target element, and any relevant data.

Example of Using Event Object

<!DOCTYPE html>
<html>
<head>
    <script>
        function showEventDetails(event) {
            console.log('Event Type:', event.type);
            console.log('Target Element:', event.target);
        }

        document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById('myButton').addEventListener('click', showEventDetails);
        });
    </script>
</head>
<body>
    <button id="myButton">Click Me</button>
</body>
</html>

Common Event Types and Examples

Mouse Events

  • Click Event
<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById('myButton').addEventListener('click', () => {
                alert('Button clicked!');
            });
        });
    </script>
</head>
<body>
    <button id="myButton">Click Me</button>
</body>
</html>
  • Mouseover Event
<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById('myDiv').addEventListener('mouseover', () => {
                document.getElementById('myDiv').style.backgroundColor = 'yellow';
            });

            document.getElementById('myDiv').addEventListener('mouseout', () => {
                document.getElementById('myDiv').style.backgroundColor = '';
            });
        });
    </script>
</head>
<body>
    <div id="myDiv" style="width: 100px; height: 100px; border: 1px solid black;">
        Hover over me!
    </div>
</body>
</html>

Keyboard Events

  • Keydown Event
<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.addEventListener('keydown', (event) => {
                console.log('Key pressed:', event.key);
            });
        });
    </script>
</head>
<body>
    <input type="text" placeholder="Type something">
</body>
</html>

Form Events

  • Submit Event
<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById('myForm').addEventListener('submit', (event) => {
                event.preventDefault();
                alert('Form submitted!');
            });
        });
    </script>
</head>
<body>
    <form id="myForm">
        <input type="text" placeholder="Enter something" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Window Events

  • Load Event
<!DOCTYPE html>
<html>
<head>
    <script>
        window.addEventListener('load', (event) => {
            console.log('Page is fully loaded');
        });
    </script>
</head>
<body>
    <p>The page is loading...</p>
</body>
</html>
  • Resize Event
<!DOCTYPE html>
<html>
<head>
    <script>
        window.addEventListener('resize', (event) => {
            console.log('Window resized:', window.innerWidth, 'x', window.innerHeight);
        });
    </script>
</head>
<body>
    <p>Resize the browser window to see the effect.</p>
</body>
</html>

Mastering events in JavaScript is essential for creating interactive and dynamic web applications. By understanding different event types, event handling techniques, and how to use the event object, you can build responsive user interfaces that react to user interactions seamlessly. Experiment with these concepts in your own projects to see how they can enhance the functionality and user experience of your web applications.

Previous Post
Newer Post

Leave A Comment

Need Help?