Monday, April 2, 2007

working with a - links in JS

Today I'm pretty happy for finding a solution to a problem I've worked around for months.
Creating nice a-links using JS.

The problem:

Writing
<a onclick="somefunction();">clickme</a>

does not give the right CSS because it seems that in order to get the proper css for a-elements, we need the HREF attribute. But if we use the HREF attribute:

<a href="#" onclick="somefunction();">clickme</a>

.. clicking on the link, will trigger the HREF attribute, and hence, in this case the page will jump to the top(or in some cases it seems pretty random) because of the #-anchor

The solution:
Return false; at the end of the onclick function

<a href="#" onclick="somefunction(); return false;">clickme</a>

The link will get the right css, and the link will not be followed after the onclick.

Good bye old solution: onmouseover="fakeLink(this);" :-)