Blog>
Snippets

'this' in an Event Handler

Showcase how 'this' can be used inside an event handler to refer to the element that received the event.
<button id='myButton'>Click me</button>
HTML markup with a button element that users can interact with.
#myButton {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
CSS styling for the button to make it visually appealing and interactive.
document.getElementById('myButton').addEventListener('click', function() {
  // Inside this function, 'this' refers to the element that received the event, which is '#myButton'.
  this.style.color = 'red'; // Changes the button's text color to red when it is clicked.
});
JavaScript code that adds a click event listener to the button. When the button is clicked, the 'this' keyword refers to the button itself and changes its text color to red.