Questions tagged [dom-events]

DOM (Document Object Model) events allow event-driven programming languages to register various event handlers/listeners on the element nodes inside a DOM tree.

JavaScript events register various event handlers/listeners on the element nodes inside an HTML document DOM tree.

There are many different ways of attaching event listeners:

  • element.addEventListener(type, listener[, useCapture]) — registers type event on element, using listener as handler. You can register multiple event listeners using this method and remove them with element.removeEventListener(). The optional useCapture parameter allows you to decide whether you want to handle it in the capture phase or in the bubbling phase. IE <= 8 doesn't support it, but has similar method: element.attachEvent(); however it doesn't have useCapture argument.
  • element.onevent = handler (where event should be replaced appropriate event name, e.g. click or load) — this was a way to register events in DOM 0. It has many drawbacks, for example you can use only one handler and it doesn't have useCapture parameter.
  • onevent HTML attributes (e.g. <button onclick="console.log('clicked');">Button</button>) — similar as element.onevent, but generally considered a bad practice because of mixing document structure (HTML) and logic (JavaScript).

References:

Links:

12471 questions
3228
votes
14 answers

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well: 1. event.preventDefault() $('a').click(function (e) { …
RaYell
  • 69,610
  • 20
  • 126
  • 152
1745
votes
9 answers

Stop setInterval call in JavaScript

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? I want the user to be able to stop the repeated refresh of data.
cnu
  • 36,135
  • 23
  • 65
  • 63
1383
votes
17 answers

window.onload vs $(document).ready()

What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?
Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163
1237
votes
11 answers

What is event bubbling and capturing?

What is the difference between event bubbling and capturing? When should one use bubbling vs capturing?
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1091
votes
24 answers

Getting the ID of the element that fired an event

Is there any way to get the ID of the element that fires an event? I'm thinking something like: $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); });
Joda
  • 12,796
  • 10
  • 34
  • 33
1063
votes
25 answers

How to make JavaScript execute after page load?

I'm executing an external script, using a