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);
2
  • 1
    So what is your actual problem? BTW, you are dispatching the event before adding the event listener. Commented May 17, 2018 at 12:28
  • Possible duplicate of Create JavaScript custom event Commented May 17, 2018 at 12:29

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

so to trigger it I have to simply call elem.dispatchEvent(event); ?
@DavidC.Yes, you only need the second argument if you want to pass some custom data through

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.