Geek Slack

Introduction to JavaScript
    About Lesson




    JavaScript Events


    JavaScript Events

    JavaScript events are actions or occurrences that happen in the browser, which can be detected and used to trigger JavaScript code.

    Common JavaScript Events

    Some common JavaScript events include:

    • click: Triggered when an element is clicked.
    • mouseover: Triggered when the mouse pointer is moved over an element.
    • keydown: Triggered when a key is pressed down while the element has focus.
    • submit: Triggered when a form is submitted.
    • load: Triggered when a resource and its dependent resources have finished loading.

    Attaching Event Handlers

    You can attach event handlers to HTML elements using either HTML attributes or JavaScript.

    HTML Attribute:

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

    JavaScript:

    const button = document.querySelector('button');
    button.addEventListener('click', function() {
        alert('Button clicked!');
    });

    Preventing Default Behavior

    You can prevent the default behavior of an event using the preventDefault() method.

    Example:

    document.querySelector('a').addEventListener('click', function(event) {
        event.preventDefault();
        alert('Link clicked, but default behavior prevented!');
    });

    Event Propagation

    Event propagation refers to the order in which events are handled when an event occurs on an element that is nested within another element.

    Example:

    document.querySelector('div').addEventListener('click', function(event) {
        alert('Div clicked!');
    });
    
    document.querySelector('button').addEventListener('click', function(event) {
        event.stopPropagation();
        alert('Button clicked!');
    });

    Understanding JavaScript events is essential for creating interactive web applications. By leveraging events, you can respond to user actions and create dynamic and engaging user experiences.