user3457884
user3457884

Reputation: 25

Delegated custom events in Javascript

I have the following snippet:

this.el.on('mousedown.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this));

What's the pure js (vanilla) equivalent of that? So far I've attempted the following but it doesn't translate:

this.el.addEventListener('mousedown.' + this.id, function(e) {
    if (e.target && e.target.matches('.textcomplete-item'))
        this._onClick.bind(this); 
});

Is the callback using this in the right context?

Upvotes: 0

Views: 36

Answers (1)

The names for DOM events are fixed. There is no mousedown.123, there is only mousedown. Also, if you just want to test for a local class, rather than needing to test a full query selector match, you can check the classList isntead.

element.addEventListener(`mousedown`, ({ target }) => {
  if (target && target.classList.contains(`textcomplete-item`) {
    element.onClick();
  }
});

However, you almost certainly don't want mousedown because now you have to also add code for touchstart, and you're going to have to make your element focussable so that people with keyboard-only (by choice or by disability) can get to your element, and then you need a keydown, and things get just plain ridiculou.

Make your element a <button>, style it with CSS to look like whatever you need it to look like, and add a single click event listener.

Upvotes: 1

Related Questions