mydomain
No ADS
No ADS

JavaScript Event Handling Tutorial with Examples

  1. Javascript Events
  2. Example with events

1. Javascript Events

No ADS
Event is a signal that something has happened. For example, you click on a button, or you close the browser, .. All DOM nodes generate such signals, but there are events other than the DOM for example, your event of closing the browser window.
Below is a list of most useful DOM events:
Mouse Events:
Event
Description
click
The event occurs when the user clicks on an element
contextmenu
The event occurs when the user right-clicks on an element to open a context menu
dblclick
The event occurs when the user double-clicks on an element
mousedown
The event occurs when the user presses a mouse button over an element
mouseup
The event occurs when a user releases a mouse button over an element
mouseenter
The event occurs when the pointer is moved onto an element
mouseleave
The event occurs when the pointer is moved out of an element
mousemove
The event occurs when the pointer is moving while it is over an element
mouseout
The event occurs when a user moves the mouse pointer out of an element, or out of one of its children
mouseover
The event occurs when the pointer is moved onto an element, or onto one of its children
Form elements events:
Event
Description
submit
When user submit a <form>.
focus
When user focus on an Element, for example <input>.
blur
When user leaves an Element, for example <input>.
Keyboard Events:
Event
Description
keydown
The event occurs when the user is pressing a key
keyup
The event occurs when the user releases a key
keypress
The event occurs when the user presses a key. (Complete 2 actions, press down and release).
Document Events.
Event
Description
DOMContentLoaded
When HTML content has loaded and processed. The DOM model has been created completely.
CSS Events:
Event
Description
animationstart
The event occurs when a CSS animation has started
animationend
The event occurs when a CSS animation has completed
animationiteration
The event occurs when a CSS animation is repeated
Event Handling:
To handle the event, you need to attach the event to a handler. the handler can be a function. When the event occurs the handler will be called to operate. The handler is a way for running Javascript codes that corresponds to user's actions.
The handler can be set in the HTML with the on{event} attribute. For example, click event:
<input value="Click me" onclick="alert('Click!')" type="button">

<input value="Click me" onclick="someFunction()" type="button">
The this object represents for the element generating the event.
<input value="Click me" onclick="someFunction(this)" type="button">
When the event occurs, Javascript creates theevent object and you can use it as a value of parameter.
<input value="Click me" onclick="someFunction(event)" type="button">
You can also access the event generating event through the event object.
var target =  event.target;

2. Example with events

No ADS
Simple and often encountered event is the event that users click on an element. Below is a simple example. The user clicks the "=" button to sum two numbers.
onclick-example.html
<!DOCTYPE html>
<html>
   <head>
      <title>Hello Javascript</title>

      <script type = "text/javascript">

         function doCalculate()  {
             var a = document.getElementById("a").value; // A String value
             var b = document.getElementById("b").value; // A String value

             var c = Number(a) + Number(b);

             document.getElementById("c").value = c;
         }
      </script>

   </head>
   <body>

      <h3>Click Event example</h3>

      <input id = "a" type="text" value= "100"/> <br/>
      + <br/>
      <input id = "b" type="text" value = "200"/> <br/>

      <button onclick="doCalculate()"> = </button> <br/>

      <input id = "c" type="text" value = ""/>

   </body>
</html>
-
The this object is the element that emits the event. You can pass this object into the event handling function.
this-obj-example.html
<!DOCTYPE html>
<html>
   <head>
      <title>Event Example</title>

      <script type = "text/javascript">

         function changeSize(target)  {
             var random = Math.round(Math.random() * 100) + 200;
             target.style.width  = random + "px";
             target.style.height  = random + "px";
         }
      </script>

   </head>
   <body>

      <h3>Event with 'this' object</h3>

      <button onclick="changeSize(this)">Click Me to Change Size</button>

   </body>
</html>
-
When the event occurs, an event object is created by Javascript. it contains tje information related to the event. For example, for the mouse event, the event object may contain the information such as the mouse position relative to the browser, the position of mouse relative to the element that emits the event, ... You can use the event object to pass in the event handling function.
<input value="Click me" onclick="someFunction(event)" type="button">
mouse-events-example.html
<!DOCTYPE html>
<html>

<head>
    <title>Javascript Mouse Events</title>

    <script src="mouse-events-example.js"></script>
    <style>
        .my-div {
            width: 290px;
            height: 100px;
            background: blue;
        }
    </style>
</head>

<body>

    <h3>Mouse Events (Enter, Move, Leave)</h3>

    <div class="my-div"
               onmouseenter="mouseenterHandler(event)"
               onmouseleave="mouseleaveHandler(event)"
               onmousemove="mousemoveHandler(event)">
    </div>

    <h3>Mouse position</h3>
    <div style="color:red;" id="position-div">

    </div>

    <h3>Statistics</h3>
    <div style="color:red;" id="statistics-div">

    </div>

</body>

</html>
mouse-events-example.js
var enterCount = 0;
var moveCount = 0;
var leaveCount = 0;


function mouseleaveHandler(evt) {
    leaveCount += 1;

    showPosition(evt);
    showStatistics();
}

function mouseenterHandler(evt) {
    enterCount += 1;

    showPosition(evt);
    showStatistics();
}

function mousemoveHandler(evt) {
    moveCount += 1;

    showPosition(evt);
    showStatistics();
}




function showPosition(evt) {
    var html = "offsetX: " + evt.offsetX +"<br/>" //
               +
               "offsetY: " + evt.offsetY;

    document.getElementById("position-div").innerHTML = html;
}

function showStatistics() {
    var html =
        "enterCount:" + enterCount + "<br/>" //
        +
        "moveCount:" + moveCount + "<br/>" //
        +
        "leaveCount:" + leaveCount;
    document.getElementById("statistics-div").innerHTML = html;
}
-
You can access the element emitting event via the event object.
event-obj-example.html
<!DOCTYPE html>
<html>
   <head>
      <title>Event Example</title>

      <script type = "text/javascript">

         function changeSize(evt)  {
             var target = evt.target;

             var random = Math.round(Math.random() * 100) + 100;
             target.style.width  = random + "px";
             target.style.height  = random + "px";
         }
      </script>

   </head>
   <body>

      <h3>Access 'target' object via 'event' object</h3>

      <button onclick="changeSize(event)">Click Me to Change Size</button>

   </body>
</html>
-
Example of a handler with multiple parameters.
multi-params-example.html
<!DOCTYPE html>
<html>
   <head>
      <title>Event Example</title>

      <script type = "text/javascript">

         function changeSize(borderColor, target, evt, bgColor)  {
             var random = Math.round(Math.random() * 100) + 100;
             target.style.width  = random + "px";
             target.style.height  = random + "px";
             target.style.borderColor = borderColor;
             target.style.backgroundColor = bgColor;
         }
      </script>

   </head>
   <body>

      <h3>A Handler has multiple parameters</h3>
      <a href="">Reset</a> <br/><br/>

      <button onclick="changeSize('red', this, event, 'green')">Click Me</button>

   </body>
</html>
No ADS

ECMAScript, Javascript Tutorials

Show More
No ADS