English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Implement some cross-browser event methods with JavaScript
Implement event binding, removal, and some commonly used event attribute acquisition with JavaScript, often considering compatibility across different browsers. Below is a cross-browser event object:
var EventUtil = { on: function(element, type, handler) {/* Add the event */ if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) {//IE Note: At this time, the event handler will run in the global scope, so the event bound by attachEvent, at this time, the this in the event handler equals window, be careful when using it element.attachEvent("on" + type, handler); } element["on" + type] = handler; } }, off: function(element, type, handler) {/* Remove the event */ if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } element["on" + type] = null; } }, getEvent: function(event) {/* Return a reference to the event object */ return event ? event : window.event; }, getTarget: function(event) {/* Return the target of the event */ return event.target || event.srcElement; }, preventDefault: function(event) { /* Cancel the default behavior of the event */ if (event.preventDefault) { event.preventDefault(); } event.returnValue = false; } }, stopPropagation: function(event) {/* Prevent event bubbling */ if (event.stopPropagation) { event.stopPropagation(); } event.cancelBubble = true; } }, /* Both the mouseover and mouserout events involve moving the mouse pointer from within the boundary of one element to the boundary of another element.*/ getRelatedTarget: function(event) { if (event.relatedTarget) { return event.relatedTarget; }//IE8 mouserout Event return event.toElement; }//IE8 mouseover Event return event.fromElement; } return null;//Other Events } } };
Call as follows:
EventUtil.on(document, "click", function(event){//Bind click event to the document element event = EventUtil.getEvent(event);//Get the event object alert("Screen coordinates: " + event.screenX + " + event.screenY); });
The article is referenced from 'Advanced JavaScript Design Third Edition'
Thank you for reading, I hope it can help everyone, thank you for your support to this site!