Reputation: 201
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);
Upvotes: 5
Views: 3491
Reputation: 66355
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>
Upvotes: 3