5

I'm trying to create custom event in vanilla javascript, but don't really understand how to trigger it. As far as I know there is jQuery method trigger('customEvent'), but how is it made in Vanilla JS? Can't find any info regarding that.

Creating CustomEvent:

var addColor = function (elem) {

    elem.classList.add('red');
    var event = new CustomEvent('madeRed');
    elem.dispatchEvent(event);
};

Attaching addEventListener to the element

var elem = document.querySelector('div');
addColor(elem);

elem.addEventListener('madeRed', function (elem) {
    elem.classList.add('color-do-changed');
}, false);
galmeriol
  • 461
  • 4
  • 14
David C.
  • 201
  • 2
  • 11
  • 1
    So what is your actual problem? BTW, you are dispatching the event before adding the event listener. –  May 17 '18 at 12:28
  • Possible duplicate of [Create JavaScript custom event](https://stackoverflow.com/questions/23344625/create-javascript-custom-event) – Ricardo Pontual May 17 '18 at 12:29

1 Answers1

3

Your code works fine, you just decided to listen to the event after calling it. Also if you want to pass custom data then pass it through detail. You didn't pass anything but were expecting the event parameter to be your element.

var elem = document.querySelector('div');

var addColor = function (elem) {
    elem.classList.add('red');
    var event = new CustomEvent('madeRed', {
      detail: {
        elem
      }
    });
    elem.dispatchEvent(event);
};

elem.addEventListener('madeRed', function (event) {
    event.detail.elem.classList.add('color-do-changed');
}, false);


addColor(elem);
.red { color: red }
.color-do-changed { text-decoration: underline }
<div>Make me red</div>
Dominic
  • 62,658
  • 20
  • 139
  • 163