开发者

Javascript detect event handlers available on HTML element

Is there a way to detect what event handlers are available natively for an HTML element?

For example:

isAvailable(img.onload) === true;    // All browsers
isAvailable(script.onload) === true; // Non-IE only (Webkit, Firefox, Opera)
isAvailable(link.onload) === true;   // IE (and I think Opera) only

Ideally I want to do feature detection in my script, where if onload is available for an element to use that, otherwise fallback. Currently I am having to do brows开发者_运维问答er forks (based on IE) which is annoying as IE may start supporting script.onload, and Webkit/Firefox may start supporting link.onload.

Unfortunately assigning element.onload makes the event no longer 'undefined', regardless of whether it will eventually fire or not.


(Edit See below, this doesn't work.) You can check whether the element has an onload property:

var img = document.createElement('img');
alert("img onload? " + ('onload' in img));
var script = document.createElement('script');
alert("script onload? " + ('onload' in script));

On IE7, I get true for the img, and false for the script.

Edit This doesn't work for Firefox. Leaving this just so others don't go down the same path.


I am not sure if this is what you were asking for, but this will let you know if you have a specific method or property available for a given object.

var apple = new Object;
    apple.load = function() { alert("I am a method.") };
    apple.color = "red"

function isAvailable(obj, mp) { 
    // obj = element to test for method or property. 
    // mp = name of method or property. 

    if (obj[mp]) {
        return true;
    } else {
        return false;
    }
}

if (isAvailable(apple, "color")) {
    alert("apple object has a 'color' property");
}

if (isAvailable(apple, "load")) {
    alert("apple object has a 'load' method");
}

Edit: Re-worked the answer to show an example.


I've done something like this before; when writing stuff for phone gap on the iphone, depending if you run the app in the simulator or on different versions of the device, you often have different handlers for handling the click of input buttons (and most other things)- so at the top of my script i just do a quick check;

var m_clickEvent = ''; 

if ( $('input').click != 'undefined')
   m_clickEvent = 'click'
else if ( $('input').tap != 'tap')
   m_clickEvent = 'tap'
else if ( $('input').touchstart!= 'touchstart')
   m_clickEvent = 'touchstart'
else 
   // some kind of error handling..

then i can go ahead and bind my event handler;

$('.myButton').bind(m_clickEvent, function(e) { ... });


Here's an example destilled from the way Modernizr does event detection:

var tmp = document.createElement('script'); 
tmp.setAttribute('onload', '');
isSupported = typeof tmp.onload == 'function';


One way I've done this in the past is to use the old "for in" loop, and check each key value to see if it starts with "on" (every native event handler I've ever seen starts this way...) So, for example:

var el = document.querySelector("*"), //this is the element (use whatever selector text)
elEventHandlers = [];                 //set up an array to hold 'em all

for (var prop in el)                  //loop through each prop of the element
    if (prop.substring(0,2)=="on")    //if the prop starts with "on" it's an event handler
        elEventHandlers.push(prop);   //so, add it to the array

console.log(elEventHandlers);         //then dump the array to the console (or whatever)

voila! Now you know what event handlers can be registered on that element!


Try this one:

var d = document.createElement('div');

if(d.hasOwnProperty('onclick')) {
    //then onclick is supported
}

you could also loop through div's(or take any other HTML element) properties to dynamically check it:

var d = document.createElement('div'),
   el = 0;

for(el in d) {
    if(d.hasOwnProperty(el)) {
        console.log(d[el]); //or do anything else you like
    }
}

You could check more on hasOwnProperty on mozilla's dev blog


isEventSupported =
    function(tag, event){
    return document.createElement(tag)[event]===null;
    };

>> isEventSupported("script", "onload"); 
true //on my current browser

There are, false reports on this event support even from veterans like..., let's not mention names - but it is NOT obvious that the onload event will most probably not fire on IMG elements SCRIPT elements and similar, because the source has already been cashed and Elements whose resources are being drawn from the cash will not fire the onload event.

Exception: the document element will fire the onload event, even when working with cashed files, because it depends on readystate complete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜