Wednesday, September 29, 2010

what's the difference between <a href="javascript:expand()"> and <a href="#" onclick="javascript:expand()">

what's the difference between <a href="javascript:expand()"> and <a href="#" onclick="javascript:expand()">


this is the outdated way and will cause problems
<a href="javascript:expand()">

and the reason this <a href="#" onclick="javascript:expand()"> scrolls to the top is
your not return false like so

<a href="#" onclick="expand();return false;">


=====================

You can use href and onclick together to provide the same functions
to people who have javascript turned off. e.g.
<a href="some.jsp?expand=1" onclick="expand(); return false;">[+]</a>

If onclick returns false, the browser never even looks at the href attribute, and so it is not followed.
Suppose a user has javascript disabled; in this case the browser ignores the onclick handler
and loads the url given in the href - which in this case is supposed to send back HTML
showing the tab expanded.

So, as jaysolomon says, you must return false if you do not want the browser to follow the href.

The other way of coding it is to ensure the expand function return false, but note, even in this case your onclick handler should include the keyword return:

<script type="text/javascript">
function expand(sec) {
// do your stuff...
return false;
}
</script>

<a href="#" onclick="return expand()">[+]</a>

=====================

all say will cause problems, but nobody says what kind of problem :)

=====================

if you have say for example a animated gif in a page and you click the javascript: protocol link the ani will quit running and you have to refresh the page to start again.

you see?

Reference:
http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20915622.html

No comments: