Sunday, May 19, 2024
79
rated 0 times [  85] [ 6]  / answers: 1 / hits: 36231  / 11 Years ago, wed, september 4, 2013, 12:00:00

This is pretty annoying. I want to just trigger an event in javascript. I need to pass the event object into the parameters as usual and an additional custom parameter.



In jQuery, this would be super easy:



$('#element').trigger('myevent', 'my_custom_parameter');


But I don't want to use this however. Every other question I have found relating to this has just suggested 'use jQuery!' It's for a plugin I'm developing and to require jQuery for one method is pretty silly. Can anyone point to a way to do the above in vanilla JS that's cross-browser compatible?


More From » custom-events

 Answers
34

You may create custom events http://jsfiddle.net/9eW6M/



HTML



<a href=# id=button>click me</a>


JS



var button = document.getElementById(button);
button.addEventListener(custom-event, function(e) {
console.log(custom-event, e.detail);
});
button.addEventListener(click, function(e) {
var event = new CustomEvent(custom-event, {'detail': {
custom_info: 10,
custom_property: 20
}});
this.dispatchEvent(event);
});


Output after click on the link:



custom-event Object {custom_info: 10, custom_property: 20} 


More information could be found here.


[#75900] Tuesday, September 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julissaimana

Total Points: 593
Total Questions: 108
Total Answers: 112

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;