Cross-browser event handlers-differences between event handlers and event objects

Source: Internet
Author: User
Tags button attributes
To handle events in a cross-browser manner, many developers use JavaScript libraries that can isolate browser differences. This article starts from the differences between event handlers and event objects, demonstrate the most appropriate event handling method for development
Basic terms:
Event An action performed by a user or a browser.
Event stream The order in which events are received from the page. The IE event stream refers to the event bubble stream, while the Netscape Communicator event stream is the event capture stream.
Event bubbling Events are received by the most specific elements (the node with the deepest nesting level in the document) at the beginning, and then gradually spread to a less specific node (document)
Event capture The node that is not specific should receive the event earlier, and the most collective node should finally receive the event
Event Handler A function (or event listener) that responds to an event)
The event stream consists of three phases: the event capture phase, the target phase, and the event bubble phase. Event Handler 
Event Handler name Description Add event Delete event
Dom0 level Assign a function to an event handler attribute. // Specify the event handler using JavaScript. First, you must obtain an object to be operated using var btn = document. getelementbyid ("mybtn"); BTN. onclick = function () {alert (this. ID );}; VaR removebtn = Document. getelementbyid ("myremovebtn"); removebtn. onclick = function () {BTN. onclick = NULL ;};
Dom2 level Methods used to process specified and delete Event Handlers: addeventlistener () and removeeventlistener (). Three functions are accepted: the name of the event to be processed, functions used as event handlers and a Boolean value (true capture phase, false bubble phase) VaR BTN = document. getelementbyid ("mybtn"); var handler = function () {alert (this. ID) ;}; BTN. addeventlistener ("click", handler, false ); VaR removebtn = document. getelementbyid ("myremovebtn"); removebtn. onclick = function () {BTN. removeeventlistener ("click", handler, false); // in most cases, add the event processing function to the bubble stage of the event stream to maximize compatibility with various browsers };
IE event handler Two methods similar to Dom are implemented: attachevent () and detachevent (). Two parameters are accepted: the name of the event handler and the function of the event handler. VaR BTN = Document. getelementbyid ("mybtn"); var handler = function () {alert ("clicked") ;}; BTN. attachevent ("onclick", Handler ); VaR removebtn = Document. getelementbyid ("myremovebtn"); removebtn. onclick = function () {BTN. detachevent ("onclick", Handler );};
There is also an HTML event handler which is not recommended. <Input type = "button" value = "Click me" onclick = "alert (& quot; clicked & quot ;) "/> <SCRIPT type =" text/JavaScript "> function showmessage () {alert (" Hello world! ") ;}</SCRIPT> because it has the following Disadvantages: 1. Different Javascript Engines follow slightly different identifier parsing rules and may encounter errors when accessing undefined object members. 2. html and JavaScript code are tightly coupled. If you want to change the event handler, you need to change the HTML and JavaScript code.
VaR eventutil = {/* parameter description: element: object to be operated type: event name handler: event handler function */addhandler: function (element, type, Handler) {If (element. addeventlistener) {element. addeventlistener (type, handler, false);} else if (element. attachevent) {element. attachevent ("On" + type, Handler);} else {element ["on" + type] = handler ;}}, removehandler: function (element, type, Handler) {If (element. removeeventlistener) {element. removeeventlistener (type, handler, false);} else if (element. detachevent) {element. detachevent ("On" + type, Handler);} else {element ["on" + type] = NULL ;}}};

 

Demo
var btn = document.getElementById("myBtn");        var handler = function(){            alert("Clicked");        };        EventUtil.addHandler(btn, "click", handler);               var removeBtn = document.getElementById("myRemoveBtn");        EventUtil.addHandler(removeBtn, "click", function(){            EventUtil.removeHandler(btn, "click", handler);        });

 

Event objectAn event that triggers the DOM generates a family object event, which contains all event-related information. Specify the element of the event (event.currenttarget,event.tar get, this; window in IE. event. srcelement or event. srcelement, this), event type (event. type) and other event-related information. preventdefault () cancels its default behavior. In addition, the stopprogation () method is used to immediately stop the propagation of events in the DOM layer, that is, to cancel further event capture or bubbling, multiple events need to be processed through a function. You can use the type attribute.
var btn = document.getElementById("myBtn");        var handler = function(event){            switch(event.type){                case "click":                    alert("Clicked");                    break;                                   case "mouseover":                    event.target.style.backgroundColor = "red";                    break;                                   case "mouseout":                    event.target.style.backgroundColor = "";                    break;            }        };               btn.onclick = handler;        btn.onmouseover = handler;        btn.onmouseout = handler;

 

Although the event objects in Dom and IE are different, cross-browser solutions can still be developed based on the similarity between them.
VaR eventutil = {/* Function Description: bind event parameter description: element: object type to be operated: event name handler: event handler function */addhandler: function (element, type, handler) {If (element. addeventlistener) {element. addeventlistener (type, handler, false);} else if (element. attachevent) {element. attachevent ("On" + type, Handler);} else {element ["on" + type] = handler ;}},/* Function Description: mouse button. When the main mouse button is clicked, the button attribute of the Click Event Dom is triggered: 0: The main mouse button 1: The middle mouse (scroll wheel) 2: the mouse button is very different for the button attributes of IE8 and earlier versions */getbutton: function (event) {If (document. implementation. hasfeature ("mouseevents", "2.0") {return event. button;} else {Switch (event. button) {Case 0: Case 1: Case 3: Case 5: Case 7: Return 0; Case 2: Case 6: return 2; Case 4: return 1 ;}}}, /* Function Description: the keyboard and text events IE8 and other versions and opere are the keycode to save characters. Other mainstream browsers support a char code attribute. In the keypress event */getcharcode: function (event) {If (typeof event. charcode = "Number") {return event. charcode;} else {return event. keycode ;}, getclipboardtext: function (event) {var clipboardData = (event. clipboardData | window. clipboardData); Return clipboardData. getdata ("text") ;}, getevent: function (event) {return event? Event: window. event;}, getrelatedtarget: function (event) {If (event. relatedtarget) {return event. relatedtarget;} else if (event. toelement) {return event. toelement;} else if (event. fromelement) {return event. fromelement;} else {return NULL ;}, gettarget: function (event) {return event.tar GET | event. srcelement;},/* Function Description: scroll wheel event */getwheeldelta: function (event) {If (event. wheeldelta) {retu RN (client. Engine. Opera & client. Engine. Opera <9.5? -Event. wheeldelta: event. wheeldelta);} else {return-event. detail * 40 ;}},/* Function Description: cancels its default behavior */preventdefault: function (event) {If (event. preventdefault) {event. preventdefault ();} else {event. returnvalue = false ;}},/* Function Description: unbind event */removehandler: function (element, type, Handler) {If (element. removeeventlistener) {element. removeeventlistener (type, handler, false);} else if (element. detachevent) {element. detachevent ("On" + type, Handler);} else {element ["on" + type] = NULL ;}, setclipboardtext: function (event, value) {If (event. clipboardData) {event. clipboardData. setdata ("text/plain", value);} else if (window. clipboardData) {window. clipboardData. setdata ("text", value) ;},/* Function Description: Stop at event propagation immediately, that is, cancel further event capture or bubble */stoppropagation: function (Event) {If (event. stoppropagation) {event. stoppropagation ();} else {event. cancelbubble = true ;}}};

 

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.