Need help for understanding Event Object

hi i can’t understand the concept of Event objects can you help me please?

Hi @alireza_alinezhad and welcome to the community :wave:

The event object contains a lot of data about the event that just happened. When we look at a click event:

  • What element was clicked? (target)
  • Where did the click happen? (clientX and clientY)
  • What type was the event? (type)
  • and many more.

When you add an event listener to a button you’ll automatically receive the event object in your callback function as a parameter. From Introduction to events: Event objects (comments by me):

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

function random(number) {
  return Math.floor(Math.random() * (number+1));
}

function bgChange(e) { /* the "e" is our name for the event object */
  const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
  e.target.style.backgroundColor = rndCol; /* Here we use "e.target" to select the button element that was clicked. */
  console.log(e);
}

btn.addEventListener('click', bgChange);

When we console.log(e) our event object, we see that there’s a lot of information.

console.log(e)
​altKey: false
​bubbles: true
​button: 0
​buttons: 0
​cancelBubble: false
​cancelable: true
​clientX: 144
​clientY: 111
​composed: true
​ctrlKey: false
​currentTarget: null
​defaultPrevented: false
​detail: 2
​eventPhase: 0
​explicitOriginalTarget: <button style="background-color: rgb(61, 247, 92);">
​isTrusted: true
​layerX: 144
​layerY: 111
​metaKey: false
​movementX: 0
​movementY: 0
​mozInputSource: 1
​mozPressure: 0
​offsetX: 0
​offsetY: 0
​originalTarget: <button style="background-color: rgb(61, 247, 92);">
​pageX: 144
​pageY: 111
​rangeOffset: 0
​rangeParent: null
​relatedTarget: null
​returnValue: true
​screenX: 2065
​screenY: 629
​shiftKey: false
​srcElement: <button style="background-color: rgb(61, 247, 92);">​
target: <button style="background-color: rgb(61, 247, 92);">
​timeStmp: 24579
​type: "click"
​view: Window https://cdpn.io/cpe/boomboom/index.html?editors=1111key=index.html-c5c3a43b-9dbb-5ab9-8ffb-a7ebdd6538aa
​which: 1
​x: 144
​y: 111
​<get isTrusted()>: function isTrusted()
​<prototype>: MouseEventPrototype { initMouseEvent: initMouseEvent(), getModifierState: getModifierState(), initNSMouseEvent: initNSMouseEvent(), … }

I hope that clears it up a bit. If you have more questions, feel free to ask. :slightly_smiling_face:

See you,
Michael

1 Like

I understood completely when you explained, Thank you Michael :smiley:

1 Like