Events are actions that an user performs on a page.
For example, clicking or positioning the mouse over an element, writing in a text input field, or scrolling the page, are events carried out by the user.
To allow you to run some JS code when these events occur, JavaScript provides us with event handlers, like: onclick, onmouseover, onkeypress, onscroll, etc.


You can see a list with JavaScript events grouped by categories, with code and examples at: coursesweb.net/javascript/events-js


Registering event handlers

The old way to execute some instructions, a function when an event is triggered, is by placing the event handler name as attribute in the HTML tag in which the event must be detected.
For example, when the user clicks on this Div, the event handler is triggered and the function someFunction() is executed:
<div onclick='someFunction();'>Content</div>

• You can also register event handlers directly in JavaScript, with this syntax:
element.event_handler = someFunction;
- element represents a HTML object that triggers the event_handler, which will execute the function someFunction.

Note that in the registration of an event handler you do not use parentheses () at the name of the function that is called.


Example, when you click on a DIV, it displays an Alert dialog box:
<h4>Example onclick</h4>
<div id='dv_1' style='background:#a8eda9; cursor:pointer; padding:8px; 12px; width:125px'>Click here</div>

<script>
var elm = document.getElementById('dv_1'); //gets the element

// function to execute when the event is triggered
function testF(ev){
 // ev.target represents the element that triggered the event
 let id = ev.target.id;
 alert('DIV id: '+id);
}

//registers onclick
elm.onclick = testF;
</script>

Event handler and Anonymous function

The function that will be executed when the event is triggered can also be created in the expresion which register the event handler.
Syntax:
element.event_handler =(ev)=>{
 //ev is the Event object
 // code to execute
};

Example:
<h4>Example event with anoymous arrow function</h4>
<div id='dv_1' style='background:#a8eda9; cursor:pointer; padding:8px; 12px; width:125px'>Click Here</div>

<script>
var elm = document.getElementById('dv_1'); //gets the element

//registers onclick
elm.onclick =(ev)=>{
 // ev.target is the element that triggered the event
 let id = ev.target.id;
 alert('DIV id: '+id);
};
</script>
• To remove the event handler, assign it the null value:
element.event_handler = null;

- Example. When the user places the cursor over the tag with id='dvid', it alerts a message, then removes the 'onmouseenter' event registration, so, when the users places again the mouse over that item, nothing happens.
<h4>Example removing event</h4>
<div id='dvid' style='width:100px; background:#a8eda9;'>Place the cursor here</div>

<script>
var elm = document.getElementById('dvid'); // gets the element

// register onmouseenter event
elm.onmouseover =(ev)=>{
 alert('Place the mouse again over that text');
 elm.onmouseover = null; // remove the registration
};
</script>

The this keyword

In JavaScript the this keyword always refers to the 'owner' of a function. In the case of event handlers, this refers to the HTML element that trigger the event.

- Example. When the user clicks on the tag with id='dvid', JavaScript gets its content, adds it into a <textarea> and changes its background color.
<h4>Example with this</h4>
<p>Click on the Div. It will call a function that adds its content in textarea and changes its background color.</p>
<div id='dvid' style='background:#a8eda9; cursor:pointer; width:125px; padding:8px 12px;'>Div, example with this</div>
<textarea id='txta'></textarea>

<script>
var elm = document.getElementById('dvid');

// registers onclick
elm.onclick = function(){
 //gets the content from the current element (that triggered the event)
 let cnt = this.innerHTML;
 document.getElementById('txta').value = cnt;

 //sets background
 this.style.background ='#bebefe';
};
</script>

this and event parameter in arrow functions

The this keyword is not recognized in the arrow functions (defined with: ()=>{} ) with the same value.
In the arrow function, this is the parent object of the function (in which it is defined).
In the arrow functions (as in all other functions) you can use the event parameter (here defined with 'ev'). It contains an object with that event; and has a property: target containing the object that triggered that event.
- In arrow functions you can use the following syntax:
var elm = event.target;

- Here is the previous example, here with arrow function and event (ev) parameter:
<h4>Example with arrow function and event parameter</h4>
<p>Click on the Div. It will call a function that adds its content in textarea and changes its background color.</p>
<div id='dvid' style='background:#a8eda9; cursor:pointer; width:125px; padding:8px 12px;'>Div, example with event.target</div>
<textarea id='txta'></textarea>

<script>
var elm = document.getElementById('dvid');

// registers onclick
elm.onclick =(ev)=>{
 //gets the content from the element that triggered the event
 let cnt = ev.target.innerHTML;
 document.getElementById('txta').value = cnt;

 //sets background
 this.style.background ='#bebefe';
};
</script>

Register and Detect events with addEventListener()

There is also another way to register events, with the addEventListener() method.
Syntax:
element.addEventListener('event', someFunction, use_capture);
- event - is a string representing the event type to listen for, without the prefix 'on' ('click', 'mouseover', 'mouseout', ...).
- someFunction - a function that is called when 'event' is dispatched.
- use_capture - (optional) a boolean value (true or false). It is meant to state whether the event handler should be executed in the capturing or in the bubbling phase. Default, false.

- Example. When the user places the mouse over a LI element, that HTML element gets a green background, and removes the background when mouseleave.
<h4>Example with addEventListener()</h4>
<p>Move the mouse cursor over the lists below.</p>
<ul>
 <li>WebDevelopment - //coursesweb.net </li>
 <li>Cursuri gratuite - //marplo.net </li>
 <li>Games - //gamv.eu </li>
</ul>

<script>
var elm_li = document.getElementsByTagName('li'); //gets all the LI tags

//function to execute when the mouseenter is triggered
function mEnter(ev){
 //sets a background color
 ev.target.style.background ='#07da08';
}

//function to execute when the mouseleave is triggered
function mLeave(ev){
 //removes background color
 ev.target.style.background ='none';
}

//traverses the object with LI elements
for(var i=0; i<elm_li.length; i++){
 //register mouseenter and mouseleave to each LI
 elm_li[i].addEventListener('mouseenter', mEnter);
 elm_li[i].addEventListener('mouseleave', mLeave);
}
</script>

Removing events registered with addEventListener

To remove an event handler registered with addEventListener(), use the removeEventListener() method:
element.removeEventListener('event', someFunction, false);
- someFunction must be the same function used in addEventListener().

Here is an example, after a certain number of triggers, the detection of the 'mousemove' event registered on a Div is canceled.
<h4>Example removes event detection registered with addEventListener</h4>
<p>Move the mouse over the following Div.<br>
When the number of triggers of the 'mousemove' event reach 12, the detection of this event is removed.</p>
<div id='dvid' style='background:#a8eda9; padding:8px; 12px; text-align:center; width:130px'>
Div - Move the mouse cursor here.<br>
<strong id='resp'>0</strong>
</div>

<script>
var elm = document.getElementById('dvid');
var resp = document.getElementById('resp');
var nre =0;

//called by mousemove
function mOver(ev){
 nre++;
 resp.innerHTML = nre;
 if(nre ==12) elm.removeEventListener('mousemove', mOver); //removes the event detection
}

//registers mousemove
elm.addEventListener('mousemove', mOver);
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add definition lists into a <dl> element?
<dt> <dd> <li>
<dl>
 <dt>HTML</dt>
  <dd> - Hyper Text Markup Language</dd>
  <dd> - Language for web pages</dd>
</dl>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility
#id {
  visibility: hidden;
}
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus
document.getElementById("id").onclick = function(){
  alert("http://CoursesWeb.net/");
}
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
$_SESSION $_GET $_REQUEST
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
}
Register event handlers, Detect and Remove events

Last accessed pages

  1. CSS Course - Free lessons (8734)
  2. PHP MySQL - WHERE and LIKE (18449)
  3. Select in MySQL, Output results in HTML Table (4794)
  4. Ajax-PHP Chat Script (37192)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (42341)

Popular pages this month

  1. Read Excel file data in PHP - PhpExcelReader (705)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (603)
  3. Insert, Select and Update NULL value in MySQL (453)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (406)
  5. PHP getElementById and getElementsByTagName (405)