Skip to content
Home ยป JavaScript Events

JavaScript Events

    Events are clicks, key press, or mouse moves. Timing and order of event cannot be predicted. Browser puts it in a queue of events, looks for event listeners and then the correct type of event is called.
    You can add event listener in different ways.

    Method #1

    addEventListener('click',processClick);
    function processClick(evt){
         alert("There was a click");
    }

    Method #2

    addEventListener(โ€˜clickโ€™, function processClick(evt){
         alert(โ€œThere was a clickโ€);
    });

    Method #3

    //anonymous function
    addEventListener('click',function (){
         alert("This is a anonymous function");
    });

    Method #4

    //windows object
    window.onclick = processClick;
    function processClick(evt){
        alert("Windows click");
    }

    Method #5

    //Directly on the HTML element
    <body>
         <button onclick="processClick()">Click Me</button>
         <script>
              function processClick(){
                  console.log(โ€œClickedโ€);
              }
         </script>
    </body>

    Event Object

    The event object is passed through the function if necessary. Every event like mouse, and keyboard has its own event properties.
    However, there are events that are common to all events

    Event PropertyDescription
    event.typereturn name of the event
    event.targetreturn HTML on which
    event took place
    event.stopPropagationstop the bubbling up of
    the event chain
    event.preventDefaultstop the default behavior of
    that results from the event.
    You can specify a new
    custom response.

    Property: evt.type

    <button id=โ€myButtonโ€>Press Me</button>
    <script>
         var b = document.querySelector(โ€œmyButtonโ€);
         b.addEventListener(โ€˜clickโ€™, processClick);
         function processClick(evt){
              alert(evt.type);
         }
    </script>

    Property : evt.target

    <button id=โ€myButtonโ€>Press Me</button>
    <script>
         var b = document.querySelector(โ€œmyButtonโ€);
         b.addEventListener(โ€˜clickโ€™, processClick);
         function processClick(evt){
              alert(evt.target);
         }
    </script>
    //Output = Object HTML Button Element

    Property : evt.preventDefault

    <body>
         <button id="myButton">Click Me</button>
         <script>
              var b = document.querySelector("#myButton");
              b.addEventListener('click', processClick);
              function processClick(evt){
                    evt.preventDefault;
              }
         </script>
    </body>
    Output = The usual button click will not respond

    In the next article, we will see different types of events for mouse, keyboard, and page.