[JavaScript] Understanding DOM event

Understanding DOM event

While working on GTPS blog, I used DOM event multiple time. It's time to understand its usage completely.

Syntax with select.onchange

when implementing a dropdown menu with select and option, a DOM event needs to be used when another value from the dropdown menu is changed.
select.onchange = (e) => {
    const newStatus = e.target.value;
    onChangeCallBack(newStatus);
}
  • select.onchange is the event that is triggered when the selected value is changed. 
  • This event is attached with a function, which take an event object (e). 
  • e.target refers to the element that triggered the event-in this case, the select element.
    • e.target.value gives the value attribute of the currently selected option within the select.
    • the value of the selected option in the dropdown at the moment the onchange event fires,

Syntax in general

e.target or event.target can be applied to any DOM event in JavaScript. The target property of the event object always refers to the specific DOM element that triggered the event, regardless of the event type.
However, e.target.value property depends on the element type:
  • For form elements like <input>, <textarea>, and <select>, e.target.value will give the current value of that element.
  • For other elements like <div>, or <span>, e.target.value will be undefined because those elements do not have a value property.

Comments