Search code examples
javascripthtmlcustom-events

custom event listener on a dom node


I want to dispatch an custom event in js from an element. It is like so:

var event = new CustomEvent("foo");
var elem = document.getElementById("bar");
elem.dispatchEvent(event);

But I cannot bind an listener for the new custom event on a dom node. With standard events it is easy. Just add an attribute on<eventName>="some javascript"

<button onclick="console.log('click!')"></button>

Is it possible also with custom elements? I tried on<elementName> and on-<elementName> but it doesn't work.

<button onfoo="console.log('foo!')"></button>
<button on-foo="console.log('foo!')"></button>

Solution

  • You could register custom events handler using addEventListener method. BTW this approach is recommended for native events as well. Inline handlers are bad because they are mixing view (HTML) with logic (js).

    var elem = document.getElementById("bar");
    
    elem.addEventListener('foo', function() {
      console.log('foo event on bar')
    })
    
    document.getElementById('foo').addEventListener('click', function() {
      var event = new CustomEvent('foo');
      elem.dispatchEvent(event);
    })
    <button id="bar">Bar</button>
    <button id="foo">Trigger Foo</button>