Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

JavaScript Event Listeners - addEventListener, onClick Examples

Events

Events are action that can be detected by JavaScript. Every element on a web page has certain events which can trigger a javascript.

  • When a user clicks the mouse.
  • When the mouse moves over an element.
  • When a user press any key.
  • When a web page has finished loading.
  • When a image has finished loading.
  • When an input field is changed.
  • When a HTML form is submitted.
Mouse EventDescription
Mouse EventDescription
onclickThis event occurs when the user clicks on an any element.
ondblclickThis event occurs when the user double-clicks on an any element.
onmouseenterThis event occurs when the mouse pointer moves onto an element.
onmouseleaveThis event occurs when the mouse pointer moves out of an element.
onmouseoverThis event occurs when the mouse pointer is moved onto an element or its children.
onmouseoutThis event occurs when the mouse pointer is moved out of an element or its children.
onmouseupThis event occurs when the user releases a mouse button while over an element.
onmousedownThis event occurs when the user presses a mouse button over an element.
onmousemoveThis event occurs when the mouse pointer is moving while it is over an element.
oncontextmenuThis event occurs when the user right-clicks on an element to open a context menu.
Keyboard EventDescription
onkeyupThis event occurs when the user releases a key.
onkeydownThis event occurs when the user is pressing a key down.
onkeypressThis event occurs when the user presses a key on the keyboard.
Form EventDescription
onblurThis event occurs when the user releases a key.
onchangeThis event occurs when the user is pressing a key down.
onfocusThis event occurs when the element gets focus.
onfocusinThis event occurs when an element is about to get focus.
onfocusoutThis event occurs when the element is about to lose focus.
oninputThis event occurs when the user input on an element.
onsearch
onselect
onsubmit
onreset
oninvalid

addEventListener - The Modern Way

addEventListener is the recommended way to attach events. It allows multiple handlers on the same element and gives you full control over event propagation.

addEventListener
const btn = document.getElementById('myBtn');

// Add event listener
btn.addEventListener('click', function(event) {
  console.log('Button clicked!');
  console.log('Target:', event.target);
  console.log('Type:', event.type);
});

// Arrow function handler
btn.addEventListener('mouseover', (e) => {
  e.target.style.backgroundColor = '#3498db';
});

btn.addEventListener('mouseout', (e) => {
  e.target.style.backgroundColor = '';
});

// Remove event listener (must use named function)
function handleClick(e) {
  console.log('Clicked at:', e.clientX, e.clientY);
}
btn.addEventListener('click', handleClick);
btn.removeEventListener('click', handleClick);

// One-time event listener
btn.addEventListener('click', () => {
  console.log('This fires only once');
}, { once: true });

Event Bubbling and Delegation

Events bubble up from the target element to the root. Event delegation uses this to handle events on many child elements with a single listener on the parent.

Event Delegation
// Event delegation - one listener handles all list items
const list = document.getElementById('myList');

list.addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    console.log('Clicked item:', e.target.textContent);
    e.target.classList.toggle('selected');
  }
});

// Stop bubbling
document.addEventListener('click', () => console.log('Document clicked'));
btn.addEventListener('click', (e) => {
  e.stopPropagation(); // prevents document handler from firing
  console.log('Button clicked - stopped bubbling');
});

// Prevent default behavior
const link = document.querySelector('a');
link.addEventListener('click', (e) => {
  e.preventDefault(); // stops navigation
  console.log('Link click intercepted');
});

// Custom events
const customEvent = new CustomEvent('userLogin', {
  detail: { username: 'Alice', timestamp: Date.now() }
});
document.dispatchEvent(customEvent);
document.addEventListener('userLogin', (e) => {
  console.log('User logged in:', e.detail.username);
});
Key Takeaways
  • Use addEventListener instead of inline HTML event attributes (onclick="...") for cleaner, maintainable code.
  • Events bubble up from the target to the document root by default - use stopPropagation() to prevent this.
  • Event delegation attaches one listener to a parent to handle events from many children - great for dynamic lists.
  • Use preventDefault() to stop the browser\'s default action (form submit, link navigation, etc.).
  • The { once: true } option in addEventListener automatically removes the handler after it fires once.
  • Custom events (CustomEvent) let you create and dispatch your own application-level events.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.