Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript OnClick cross-browser friendly?

Can I use the following across all browsers?

<a href="#" onclick="doSomething()">Click here.</a>

Is this "bad practice" in regards to standards?

Will it work on IE, FF, Safari and Chrome?

like image 684
Moshe Avatar asked Aug 19 '10 21:08

Moshe


2 Answers

Can I use the following across all browsers?

Yes

Is this "bad practice" in regards to standards?

"Bad practice" and "Standards compliance" are different things. It is standards compliant, but also, for three reasons, bad practice.

  1. It is not unobtrusive. Event handlers are better applied with JS.
  2. It links to the top of the page (#) and will always send the browser there, even if the JS runs.
  3. If the JS fails, then nothing useful will happen. You should build on stuff that works.

Will it work on IE, FF, Safari and Chrome?

Yes

like image 104
Quentin Avatar answered Oct 13 '22 14:10

Quentin


Despite some people might say, it's not bad practice (with the caveat that it's the only event listener you want on this element), and it is the simplest (and most prevalent) cross-browser way to add an event listener, but there are two changes I would make to it.

First of all, if Javascript is not enabled, the link will be useless (although the # href will make the browser scroll to the top of the page, which probably isn't desired). Similarly, with Javascript enabled, clicking on the link will still cause the browser to follow the href, and scroll up.

Instead, I'd use something like this:

<a href="[url to JS-less way of doing the same thing]" onclick="doSomething(); return false">Click here</a>

Alternately, if it really is a javascript-only thing, you could make the link hidden by default using CSS and use Javascript to make it visible (so that users with JS disabled won't see a useless link).

like image 29
Daniel Vandersluis Avatar answered Oct 13 '22 15:10

Daniel Vandersluis