JavaScript Tutorial Series - DOM Events

In JavaScript, DOM events capture actions a user performs on an HTML element in a web application. Examples of user actions include clicking on a button or link, entering text into an input field or selecting an item from a list. To capture a user event, JavaScript has action listeners. Action listeners define a callback function that performs a certain set of instructions when an event occurs on a given HTML element. HTML elements have HTML event attributes. The following is a list of commonly used event attributes to capture mouse and keyboard events: onclick ondblclick onmousedown onmousemove onmouseout onmouseover onmouseup onkeydown onkeypress onkeyup The following is an example to perform a specific action when a button is clicked:


In an HTML file, define the button:

  <button id='testbutton'>Test</button>


In a JavaScript file, define the event handler:

  document.getElementById('testbutton').onclick = function(evt) {
    console.log(evt.target.id + ' was clicked');
  }

The evt variable is the HTML element that received the action. It can be used to access information about the HTML element. In the followng example, the button is changed to a div and the same click handler added. The div can then be styled to create a custom button:


In an HTML file, define the div:

  <div id='testbuttondiv'>Test</div>


In a JavaScript file, define the event handler:

  document.getElementById('testbuttondiv').onclick = function(evt) {
    console.log(evt.target.id + ' was clicked');
  }
Event handlers may also be defined using the addEventListener function. Example:


In an HTML file, define the div:

  <div id='testbuttondiv'>Test</div>


In a JavaScript file, define the event handler:

  document.getElementById('testbuttondiv').addEventListener('click', function(evt) {
    console.log(evt.target.id + ' was clicked');
  }, false);
  
The event handler function may also be defined directly on the HTML element as shown below:


In an HTML file, define the div:

  <div id='testbuttondiv' onclick="console.log(testbuttondiv was clicked');" >Test</div>
  
I usually use the first approach since it is simpler and easier to read. I don't use the third method because it is cleaner to put JavaScript code in a separate .js file rather than inlined inside the HTML. A complete list of HTML event attributes can be found here: https://developer.mozilla.org/en-US/docs/Web/Events (#sponsored)

More JavaScript








Comments