JS Event Handlers

JS Event Handlers

JavaScript Event Handlers are functions that get triggered when a specific event occurs on a web page. An Event is an action or occurrence that happens in the browser, such as a user clicking a button, hovering over an element, or scrolling down the page.

To use an Event Handler, you need to select the element that you want to target, and then assign the handler function to it.

One way to assign an Event Handler is by using the addEventListener() method. This method takes two arguments: the name of the event and the function to be executed when the event occurs.

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

button.addEventListener('click', () => {
  alert('Button clicked!');
});
  • The querySelector() method is used to select the button element on the page.
  • The addEventListener() method is used to add a click Event Handler to the button.
  • The function passed to the addEventListener() method will be executed when the button is clicked.

You can also assign Event Handlers directly in HTML using inline event handlers. Inline event handlers are placed within an HTML tag and are executed when the specified event occurs.

<button onclick="alert('Button clicked!')">Click me</button>
  • The onclick attribute is used to assign an Event Handler to the button element.
  • The function specified in the attribute will be executed when the button is clicked.

However, using inline event handlers is generally not recommended as it can make the HTML code difficult to read and maintain. It is better to use addEventListener() or other JavaScript libraries like jQuery to add Event Handlers to your web page.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe