Events in JavaScript

What is an event?

An event is a particular occurrence in the browser. Using JavaScript, we can tell how the element(s) in a webpage should "react" when this specific event occurs.

Example: we can display an alert when the page loads.

Events can be broadly classified into various types:

  • Load events - This event fires on the window object, images, script tags, and link tags. Example: To display an error message when an error occurred while loading an image or a video.

  • Click events - Most commonly used for buttons. Also can be used in paragraphs, divs, images, etc., Example: To perform calculations when a button is double-clicked.

    • Submit event - It fires on the form element. This event is also similar to the click event.
  • Keyboard events - This is mostly used on the input elements. Example: To change the background color of the input element when releasing/pressing a key.

  • Mouse events - This can be used in any element. Example: To highlight a paragraph when hovering over it.

How do we associate an event with an element?

  1. To get the target element from a web page using selectors like id, class, tags, etc.,

  2. Mention the event name in addEventListener function as the first argument and the event handler function name as the second argument.

<!DOCTYPE html>
<html lang="en">
<body>
    <p id="highlight-para">
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nisi numquam harum sequi in possimus id dignissimos quae officiis minus dolor tenetur, repellendus hic aliquid consequatur beatae eos consectetur fuga! Praesentium.
    </p>
    <p>
        This is some randome text.
        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequuntur soluta animi eum inventore id. Voluptatem corporis totam dicta corrupti a tempore ab adipisci tenetur non, laboriosam repellat illum in accusantium!
    </p>
    <script>
        // Target the required element
        let para = document.getElementById("highlight-para"); 

        //change the background color of the paragraph to blue when user hover over the "highlight-para"
        function mouseOverHandler(){
            para.style.backgroundColor = "blue" 
        }

        //Instructing the browser on how it should react when user does any specific action/event on any element
        para.addEventListener("mouseover", mouseOverHandler)
    </script>
</body>
</html>

In the above example, when the user hover over the first paragraph with id "highlight-para", mouseOverHandler function is being called and changes its background color to blue. The second paragraph will not change its background color as we did not target the element in javascript.

Reference: https://www.w3schools.com/jsref/dom_obj_event.asp