DOM - Event Object (Callback function parameter)

1 - About

A event callback function may have a parameter specified with a name such as event, evt, or simply e. This is the event object, and it is automatically passed to the callback function to provide extra features and information.

The target property of the event object is always a reference to the element that the event has just occurred upon.

3 - Target

The target attribute of an object event represents the element where the event was fired.

https://developer.mozilla.org/en-US/docs/Web/API/Event/target

3.1 - Style


var btn = document.querySelector('button');

function bgChange(e) {
  var rndCol = 'rgb(' + Math.round(Math.random()*255) + ',' + Math.round(Math.random()*255) + ',' +Math.round(Math.random()*255) + ')';
  e.target.style.backgroundColor = rndCol;
  console.log(e.toString());
  console.log(e);
}  

btn.addEventListener('click', bgChange);


<button class="btn btn-info">Poke me</button>

3.2 - data

HTML - Data attributes


document.body.addEventListener('click', (event) => {
    if (event.target.dataset.echo) {
        console.log('The target element has a data-echo attribute. Hello '+event.target.dataset.echo+' !')
    } else {
       console.log('The target element has NOT a data-echo attribute')
    }
})


<div data-echo="nico">Click Me to Hello Nico</div>
<div >Click Me to see that there is no data attribute</div>


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap