Browser Feature Detection (2)-General event detection-jquery

Source: Internet
Author: User
In the previous article, we introduced several browser feature detection solutions and specific purposes added in jQuery1.4. This article will focus on events and introduce a complete and general event detection solution. In the previous article, we introduced several browser feature detection solutions and specific purposes added in jQuery1.4. This article will focus on events and introduce a complete and general event detection solution.

Event detection is used to detect whether an event exists (available) in different browsers. This is also very important during Javascript writing. For example, the mouseenter/mouseleave event is practical, but not all browsers provide standard support, so you need to manually simulate it yourself, that is:

Function addEvent (element, name, handler) {if (name = 'mouseenter '&&! HasEvent (name, element) {// simulate a mouseenter event by other means} // normal event registration };

This article focuses on the specific implementation of hasEvent in the above Code.

Basic Solution

The most basic event detection method must begin with the event registration method.

There are usually three registration methods for events, one of which is inline, that is, declaring events in HTML through attributes, such:

CLICK ME

The code above creates a button tag and registers a click event.

Another solution is to register an event by directly assigning values to onclick:

document.getElementById('myButton').onclick = function() { alert('CLICKED!'); };

From the above two event registration methods, we can find that onclick is an attribute of the button tag, and event registration can be completed by assigning values to it.

Therefore, the most basic event detection solution is to check whether the on [event name] attribute exists in the DOM element. Therefore, there is the simplest version:

function hasEvent(name, element) { name = name.indexOf('on') ? 'on' + name : name; element = element || document.createElement('p'); var supported = name in element; };

It should be noted that an event exists in the form of on [event name] as an element attribute. Therefore, in terms of universality, add 'on' to the event name when necessary. In addition, it is a common function to determine whether an event is available. If no specific element is specified, the most widely used p element can be used as an alternative.

Some tag-specific events

Some events are unique to some elements and generally include the following:

  • Unique form events: submit, reset

  • Unique input events: change, select

  • Unique img events: load, error, abort

Considering the existence of these events, using the p element sometimes produces incorrect results. Therefore, when creating a general substitution element, you can use a dictionary to maintain the element tag name to be created:

var hasEvent = (function() { var tags = { onsubmit: 'form', onreset: 'form', onselect: 'input', onchange: 'input', onerror: 'img', onload: 'img', onabort: 'img' }; return function(name, element) { name = name.indexOf('on') ? 'on' + name : name; element = element || document.createElement(tags[name] || 'p'); supported = name in element; } })();

Using the closure to use tags as a static dictionary can reduce the overhead of object generation to a certain extent.

DOM pollution

The reason why DOM elements have an attribute similar to onclick is that this attribute exists in the _ proto _ of DOM element objects. Due to the weak type mechanism of Javascript, external code can affect the result of the hasEvent function by adding properties to _ proto _. For example, the following code produces incorrect results in Firefox and Chrome:

document.createElement('p').__proto__.ontest = function() {}; var supported = hasEvent('test', document.createElement('p')); //true

In the above example, although the _ proto _ attribute is modified and hasEvent is called, different p objects are used, however, because _ proto _ is essentially an object in the prototype chain, it affects all p objects.

In order to deal with this situation, you need to try to delete the corresponding attribute in the _ proto _ attribute. Because the native type attribute has the DontDelete tag, you cannot use the delete keyword to delete it, therefore, the following logic can be appended to the hasEvent function for more secure judgment:

var temp; if (supported && (temp = proto[name]) && delete proto[name]) { supported = name in element; proto[name] = temp; }

The logic is very simple. Try to append _ proto _ and try again. Of course, don't forget to change the original value back.

Firefox BUG

Unfortunately, the hasEvent function provided previously does not work perfectly in Firefox. Running the following code in Firefox will result in false:

Alert ('onclick' in document.doc umentElement); // Firefox pops up with false

Therefore, you need to rebuild the hasEvent function to support Firefox. In most browsers, after an element registers an event in inline mode, you can use element. on [event name] to obtain the registered function object. For example:

CLICK ME 
Related Article

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.