The event model varies with browsers.

Source: Internet
Author: User
Document directory
  • 1. Only IE Opera supports binding and unbinding Event Listeners using the 'tachevent' and 'detachevent' methods.
  • 2. Differences between browsers in obtaining event objects
  • 3. Differences in properties and methods of event objects in various browsers
  • 1. Use features to determine whether to bind and unbind functions to event listeners without compatibility issues
  • 2. Use features to determine to obtain valid event objects
  • 3. Use features to determine the use of non-standard methods and properties corresponding to the standard

Standard Reference

According to W3C DOM 2 Events, the EventTarget interface is implemented by all nodes that support the DOM event model. This interface provides the 'addeventlistener 'and 'removeeventlistener' methods to bind or unbind an EventListeners interface to an EventTarget.

DOM 2 Events defines the Event interface to provide the context information of the Event. It provides several standard attributes and methods. Objects that implement the Event interface are generally passed into the Event handler as the first parameter to provide information related to the current Event.

The DOM 2 event model allows DOM to implement multi-module support for events. If necessary, the event model allows the addition of new event modules. For the purpose of common usage, DOM defines a low-level, device-dependent event module, a UI logic event module, and a UI event module of a document change event module. When a third-party implementation (such as a browser vendor) defines a new type of event, the event name must not start with a case-insensitive 'dom 'string, this prefix is reserved for future DOM Event modules.

DOM 2 has defined a UI event type module and a mouse event type module, which correspond to the UIEvent and MouseEvent interfaces respectively. These two interfaces provide several standard attributes and methods to learn some information about an event.

For more information about the EventTarget interface, see DOM 2 Events 1.3. Event listener regiener.

For more information about the Event interface, see DOM 2 Events 1.4. Event interface.

For more information about the Event module, see DOM 2 Events 1.6. Event module definitions.

Problem description

The methods used by browsers to bind and unbind Event listeners to elements, obtain Event objects, and implement Event objects are different.

Impact

If you use a browser-specific event-related property and method to write code, it may cause compatibility issues, leading to code errors and function failure.

Affected browsers
All browsers
Problem Analysis 1. Only IE Opera supports binding and unbinding Event Listeners using the 'tachevent' and 'detachevent' methods.

According to the description in DOM 2 Events, the node uses the 'addeventlistener 'and 'removeeventlistener' methods to bind and unbind event listeners. However, IE6 IE7 IE8 does not support these two methods, opera supports both the 'tachevent' and 'detachevent' methods. Chrome Safari Firefox only supports standard methods.

Analyze the following code:

<button id="add" type="button">add event listener test</button><button id="remove" type="button">remove event listener test</button><div id="info"></div><script type="text/javascript">var add = document.getElementById("add"),remove = document.getElementById("remove"),showMsgA = function(){showMsg("attachEvent")},showMsgB = function(){showMsg("addEventListener")};if(add.attachEvent){add.attachEvent("onclick",showMsgA);remove.attachEvent("onclick",removeE);}if(add.addEventListener){add.addEventListener("click",showMsgB,false);remove.addEventListener("click",removeE,false);}function removeE(){if(add.detachEvent){add.detachEvent("onclick",showMsgA);showMsg("detachEvent");}if(add.removeEventListener){add.removeEventListener("click",showMsgB,false);showMsg("removeEventListener");}}function showMsg(method){document.getElementById("info").innerHTML += ("support " + method + "<br />");}</script>

Choose 'add event listener test'> 'remove event listener test'> 'add event listener test' to test the support of these methods in various browsers. The result is as follows:

IE6 IE7 IE8
Opera
Chrome Safari Firefox

Pay attention to the following points for 'addeventlistener 'and 'attachevent:

  • IE does not support triggering event listeners during the capture phase. The 'tactachevent' method does not provide parameters to indicate whether to respond to events triggered during the capture phase;
  • Both 'addeventlistener 'and 'tachevent' can register multiple event listeners;
  • Register the same event listener for the same event multiple times in Firefox Chrome Safari Opera, and the event listener for repeated registration will be discarded; the event listener for repeated registration in IE will be repeatedly executed multiple times;
  • When multiple event listeners are registered for the same element, the execution sequence of IE6 IE7 Event Listeners is random, IE8 is inverted, and Firefox Chrome Safari Opera is sequential;
  • When an event listener registered with an element contains an invalid event listener (non-function), an exception is thrown in IE Firefox, while an invalid event listener is ignored in Chrome Safari Opera, continue to execute other event listeners.
2. Differences between browsers in obtaining event objects

DOM 2 Events specifies that the first parameter of the event listener is used as the event object, While IE Opera Chrome Safari also supports obtaining event objects through window. event.

Analyze the following code:

<button type="button" id="attach">attachEvent</button><button type="button" id="addE">addEventListener</button><button type="button" id="byclick">onClick</button><br />INFO :<div id="info"></div><script type="text/javascript">function $(id){return document.getElementById(id);}var attach = $("attach"),addE = $("addE"),byClick = $("byclick");attach.attachEvent && attach.attachEvent("onclick", handler);addE.addEventListener && addE.addEventListener("click", handler, false);byClick.onclick = handler;function handler(){var src = window === this ? window.event.srcElement : this, type = src.innerHTML;window.event && showMsg(window.event.type, type + " + window.event");arguments[0] && showMsg(arguments[0].type, type + " + arguments[0]");}function showMsg(type, msg){$("info").innerHTML += (msg + "(type : " + type + ")<br />");}</script>

The above code combines different event listener binding methods and event object acquisition methods to test the support of various browsers.

Click 'tachevent'> 'addeventlistener '> 'onclick'. The result is as follows:

IE6 IE7 IE8
Chrome Safari
Opera
Firefox

The following table lists the test results.

Event object Acquisition Method IE6 IE7 IE8 Chrome Safari Opera Firefox
Window. event Y Y Y N
Arguments [0] Y2 Y Y Y

Note 1: Y indicates that the event object acquisition method is supported, and N indicates that it is not supported.

NOTE 2: partially supported.

From the table above, we can see that:

  • Only when the attachEvent method is used to register the event listener can IE use the first parameter passed in by the event listener as the event object;
  • Chrome Safari Opera supports both methods to get event objects;
  • Firefox only supports standard methods for obtaining event objects.
3. Differences in properties and methods of event objects in various browsers

IE has limited support for standard attributes and methods of event objects. For most attributes and methods, IE provides a set of alternative non-standard alternatives; in addition to fully supporting the standard attributes and methods of event objects, Firefox Chrome Safari Opera also supports non-standard alternatives provided by IE to varying degrees.

The following code detects the support of Event, UIEvent, MouseEvent interface, and non-standard attributes of Event objects in various browsers:

<button type="button" id="iEvent">Interface Event</button><button type="button" id="iUIMouse">Interface UIEvent & MouseEvent</button><input type="text" id="nosK" /><p id="wrap" style="border:3px solid;padding:5px;width:500px;"><a id="nosCM" href="#"></a></p><br /><table border="1"><tbody><tr><th>Interface Event</th><td id="einfo"></td></tr><tr><th>Interface UIEvent<br/>&<br/>MouseEvent</th><td id="minfo"></td></tr><tr><th>Non-standard<br/>&<br/>click</th><td id="ncinfo"></td></tr><tr><th>Non-standard<br/>&<br/>mouseover mouseout</th><td id="nminfo"></td></tr><tr><th>Non-standard<br/>&<br/>keyCode</th><td id="nkinfo"></td></tr></tbody></table><script type="text/javascript">function $(id){return document.getElementById(id);}function addEvent(elem, type, handler, useCapture){elem.addEventListener ? elem.addEventListener(type, handler, useCapture) :elem.attachEvent("on" + type, handler);}addEvent($("iEvent"), "click", handleEvent, false);addEvent($("iUIMouse"), "click", handleUIMouse, false);addEvent($("nosCM"), "click", handleNoSClick, false);addEvent($("wrap"), "click", function(){alert("P tag.");}, false);addEvent($("nosCM"), "mouseover", handldNoSMouse, false);addEvent($("nosCM"), "mouseout", handldNoSMouse, false);addEvent($("nosK"), "keydown", handleNoSKey, false);addEvent($("nosK"), "keypress", handleNoSKey, false);addEvent($("nosK"), "keyup", handleNoSKey, false);function handleEvent(e){e = e || window.event;var props = {type : "type",target : "target",currentTarget : "currentTarget",eventPhase : "eventPhase",bubbles : "bubbles",cancelable : "cancelable",timeStamp : "timeStamp",initEvent : "initEvent",preventDefault : "preventDefault",stopPropagation : "stopPropagation"};showMsg(props, e, $("einfo"));}function handleUIMouse(e){e = e || window.event;var props = {view : "view",detail : "detail",initUIEvent : "initUIEvent",screenX: "screenX",screenY : "screenY",clientX : "clientX",clientY : "clientY",ctrlKey : "ctrlKey",shiftKey : "shiftKey",altKey : "altKey",metaKey : "metaKey",button : "button",relatedTarget : "relatedTarget",initMouseEvent : "initMouseEvent"}showMsg(props, e, $("minfo"));}function handleNoSClick(e){e = e || window.event;e.returnValue = false;e.cancelBubble = true;var props = {cancelBubble : "cancelBubble",offsetX : "offsetX",offsetY : "offsetY",returnValue : "returnValue",srcElement : "srcElement",x : "x",y : "y"};showMsg(props, e, $("ncinfo"));}function handldNoSMouse(e){e = e || window.event;var props = {fromElement : "fromElement",toElement : "toElement"};showMsg(props, e, $("nminfo"));}function handleNoSKey(e){e = e || window.event;$("nkinfo").innerHTML += "<strong>" + e.type + "</strong> : " + e.keyCode + "<br/>";}function showMsg(props, e, info){var tmp = "", p, val;with(e){for(p in props) {try{val = eval(props[p]) + " [" + typeof eval(props[p]) + "]";} catch (e) {val = undefined;}tmp += "<strong>" + p + "</strong> : " + val + "<br />"}}info.innerHTML = tmp;}</script>

Run the preceding test code, click the 'interface event' button, 'interface UIEvent & mouseevent' button, and move the cursor over the image, and then move it away. In the text box, enter 'A ', the results are as follows: 3

Interface & Non-standard Property & method IE6 IE7 IE8 Chrome Safari Opera Firefox
Interface Event Type Y Y Y
Target N Y Y
CurrentTarget N Y Y
EventPhase N Y Y
Bubbles N Y Y
Cancelable N Y Y
TimeStamp N Y Y
InitEvent N Y Y
PreventDefault N Y Y
StopPropagation N Y Y
Interface UIEvent View N Y Y
Detail N Y Y
InitUIEvent N Y Y
Interface MouseEvent ScreenX Y Y Y
ScreenY Y Y Y
ClientX Y Y Y
ClientY Y Y Y
CtrlKey Y Y Y
ShiftKey Y Y Y
AltKey Y Y Y
MetaKey N Y Y
Button Y Y Y
RelatedTarget N Y Y
InitMouseEvent N Y Y
Non-standard CancelBubble Y Y Y
OffsetX Y Y N
OffsetY Y Y N
ReturnValue Y Y N
SrcElement Y Y N
X Y Y N
Y Y Y N
FromElement Y Y N
ToElement Y Y N
KeyCode Y Y Y

NOTE 3: Y indicates that the event object supports this attribute or method, and N indicates not.

From the table above, we can see that:

  • IE supports all non-standard attributes of the Event object, does not support all method attributes and methods of the Event interface except 'type', and does not support all properties and methods of the UIEvent interface, the 'metake', 'relatedtarget' attributes, and 'initmouseevent' methods of the MouseEvent interface are not supported;
  • Chrome Safari Opera supports all standard and non-standard attributes and methods of event objects;
  • Firefox supports all standard attributes and methods of the event object, but only supports 'cancelbucket' and 'keycode' in non-standard attributes '.

Note that:

  • Firefox does not support the 'returnvalue' attribute of the event object. Although the 'returnvalue' value is false in the test sample, it is only because the 'returnvalue' attribute is added to the event object, it does not play the role of canceling the default action of the event. It can be seen from the address bar that the '#' is added, which is caused by the 'href 'attribute of the tag.
  • Different browsers return different values for the 'timestamp' attribute of the Event interface.

For more information about non-standard properties and methods of event objects implemented by IE, see MSDN event Object.

For more information about Firefox's implementation of event objects, see MDC event.

Solution 1. Use features to determine whether to bind and unbind functions to event listeners without compatibility issues

For example:

function addEvent(elem, type, handler, useCapture){elem.addEventListener ? elem.addEventListener(type, handler, useCapture) :elem.attachEvent("on" + type, handler);}function removeEvent(elem, type, handler, useCapture){elem.removeEventListener ? elem.removeEventListener(type, handler, useCapture) :elem.detachEvent("on" + type, handler);}
2. Use features to determine to obtain valid event objects

In the event listener, determine whether the first parameter or window. event is valid, for example:

function handler(e){e = e || window.event;}
3. Use features to determine the use of non-standard methods and properties corresponding to the standard

Although IE has limited support for standard attributes and methods of event objects, its own event model can basically replace or implement the functions of standard attributes or methods.

The following table summarizes some non-standard attributes that correspond to standard event objects or can implement standard attributes or method functions:

Standard Non-standard
Target SrcElement
PreventDefault () ReturnValue
StopPropagation () CancelBubble
RelatedTarget FromElement toElement

In addition, the standard 'clientx' and non-standard 'X' attributes share the same role, and the same applies to 'clienty' and 'y.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.