Events in JavaScript

  • What is Events ?
  • Events in JavaScript are actions or occurrences that happen in the web browser, which can be used to trigger responses in your code. They are a fundamental part of web development, enabling interactive behavior on web pages. Events can be triggered by user actions like clicking, typing, or moving the mouse, as well as by system-generated events like page loading.
    Here are some examples of events...

  • hold alt key & click :
  • JavaScript code
    <html> <body onmousedown="Key(event)"> <p align="center">PBA INSTITUTE</p> <script> function Key(event) { if (event.altKey) { alert("The ALT key was pressed!"); } else { alert("The ALT key was NOT pressed!"); } } </script> </body> </html>

    Output :

  • Ctrl key events :
  • JavaScript code
    <!DOCTYPE html> <html> <body onmousedown="KeyPressed(event)"> <p>PBA INSTITUTE</p> <script> function KeyPressed(event) { if (event.ctrlKey) { alert("The CTRL key was pressed!"); } else { alert("The CTRL key was NOT pressed!"); } } </script> </body> </html>

    Output :

  • Coordinates events x & y :
  • JavaScript code
    # Mouse over the rectangle above to get the horizontal and vertical coordinates of your mouse pointer <!DOCTYPE html> <html> <head> <style> div { width: 100px; height: 100px; border: 3px solid black; } </style> </head> <body> <div onmousemove="Coords(event)" onmouseout="clearCoor()"></div> <p id="pba"></p> <script> function Coords(event) { var x = event.clientX; var y = event.clientY; var coor = "X coords: " + x + ", Y coords: " + y; document.getElementById("pba").innerHTML = coor; } function clearCoor() { document.getElementById("demo").innerHTML = ""; } </script> </body> </html>

    Output :

  • Relates target :
  • JavaScript code
    The relatedTarget property returns the element related to the element that triggered the mouse event. <html> <body> <p onmouseover="get(event)"> PBA INSTITUTE</p> <script> function get(event) { alert(event.relatedTarget.tagName); } </script> </body> </html>

    Output :

  • Conclusion :
  • Understanding events in JavaScript is crucial for creating interactive web applications. By effectively using event listeners, handling event objects, and managing event propagation, you can build dynamic and responsive user interfaces.