Use onsearch on Chrome but onsubmit on non-supporting browsers?

Viewed 57

If I have HTML along the lines of

<form onsubmit="HandleOnSubmit()">
    <input type="search" id="query" onsearch="HandleOnSearch()">
</form>

... then how would I have browsers supporting onsearch (like Chrome) only use HandleOnSearch(), and non-supporting browsers (like Firefox, at the time of writing) use HandleOnSubmit()? Right now, Chrome (which doesn't need HandleOnSubmit) fires twice, first the outer, then the inner event. Thanks!

(If nothing else works, I'll do a !Chrome check in HandleOnSubmit, but I figured there might be something better I'm missing.)

1 Answers

Feature detection

Generally speaking, the answer to any question of the form "how do I use a feature available only in some browsers" is to use feature detection:

  1. at runtime, your code programmatically checks for the existence of the feature, or confirms that it supports some option you need, etc
  2. based on the results of that check, you invoke either the special behavior or some fallback behavior

There are libraries out there that do all the feature detection up-front and publish those results such that your app can get the answers easily (perhaps by looking for a CSS class on the <html> element), but a quick-and-dirty approach might be:

  1. create an <input type="text" /> in memory
  2. attach a search handler to it (using element.addEventListener('search', ...))
  3. manually fire the search event on the element
  4. your search handler sets a flag
  5. return the value of the flag: if it was set, this browser supports onsearch; if not, the browser does not
Related