If you are using jQuery, then attaching an event to the body of the document is as simple as:
$('document.body').on('.M', 'click', function (){
alert("IT WORKS");
});
With vanilla JavaScript, it’s a bit more long winded, and ends up being:
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'M') {
alert("IT WORKS");
}
}, false);
With all of those other events that you want to add, they can get a bit long-winded so you can reduce the amount of repetition by using a separate function to connect things together.
Here’s an example using the “It works” part.
function itWorks() {
alert("IT WORKS");
}
function addClassEventHandler(className, eventType, eventFunc) {
document.body.addEventListener(eventType, function (evt) {
if (evt.target.className === className) {
eventFunc(evt);
}
});
}
addClassEventHandler('M', 'click', itWorks);
With that addClassEventHandler function, your code will be as easy as this:
addClassEventHandler('M', 'dragstart', dragStarted);
addClassEventHandler('M', 'dragover', draggingOver);
addClassEventHandler('M', 'dragleave', draggingLeave);
addClassEventHandler('M', 'drop', dropped);
addClassEventHandler('M', 'click', function (evt) {
editUldDetails(evt.target);
});
Here’s a quick demo of this in action: http://jsfiddle.net/xftx0phk/1/
The main benefit here is that instead of the page having to juggle thousands of event handlers on the page, it instead has an easier time handling just a few handlers attached to the body.