Domanda

I have a search input on an HTML 5 page that I need to work in multiple browsers:

<input type="search" placeholder="type here..." />

I detect whether the browser supports search by seeing whether the browser rendered it as a search input or a regular text one:

var supportsHtml5Search = !!(inputDomElement.type !== 'text');
if (supportsHtml5Search) {
    inputDomElement.addEventListener('search', searchFunction);
}
else {
    // This browser doesn't support onsearch event, so handle keyup instead
    inputDomElement.addEventListener('keyup', searchFunction);
}

This worked fine - Chrome and Safari used the onsearch event (which also helpfully fires when they hit the clear X icon) and IE used the keyup event (with some additional checks not shown here).

However that seems to be broken in IE10, which displays a search exactly the same as an <input type="text" /> (like IE9 and below) and returns search as the type (like Chrome/Webkit), but doesn't fire the onsearch event.

Is there a better way to detect search input support?

What is the best way to sniff for this feature's support?

È stato utile?

Soluzione

This article describes quite a robust way of detecting the event support itself - as your case is yet another one when it's different from the feature support.

Basically, one has to test a corresponding property (onsearch for search event, for example) of the corresponding elements. Like...

'onsearch' in document.documentElement; // true in Chrome, false in Firefox/Opera

It's noted in the article that Firefox will fail the check if it's done on the wrong element, but I actually found only Opera behaving that way:

'onchange' in document.documentElement; // false in Opera, true in Firefox/Chrome
'onchange' in document.createElement('input'); // true in Opera too

As a final resort, one can attempt to assign a handler for this element, then check this property again:

var el = document.createElement('input'); 
el.setAttribute('onsearch', 'return;'); 
typeof el.onsearch; // 'function' in Chrome, 'undefined' in Firefox/Opera
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top