Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The return false onclick anchor not completely working

I have a lightbox overlay and I'm using the below to cancel out the browser window scroll for the href anchor of "#". I have it working so it doesn't scroll the window on the initial click however upon closing the lightbox overlay the browser scrolls to the top and # is appended to the URL.

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

or even this...

<a href="javascript:void(0)" onclick="somefunction(); return false;">...

The link is on a clickable image which the onclick function fires the overlay to pop up.

Andy ideas how to prevent the browser from scrolling to top upon exiting the overlay?

like image 616
RonnieT Avatar asked Apr 13 '11 05:04

RonnieT


2 Answers

I'd suggest not using an anchor tag at all. If you don't want an HREF value, then it's really not a link to another page, so probably not truly a link. If the site has to be accessible sans javascript, then you need to think about this some more and come up with a solution that will allow for a true href value that will link to the actual content.

However, if you're OK with this being a JS-required app, then you can do this:

<a href="javascript:;" onclick="somefunction(); return false;">

But, again, this is really something you are clicking on to update the UI rather than go somewhere, so I'd just make it a DIV, give it an onclick event, and be done with it. But be sure to give the div a tabindex so that it can be keyboard-accessible.

like image 84
DA. Avatar answered Oct 05 '22 09:10

DA.


You should avoid the # href and the javascript: pseudo protocol.

A link should always point to a valid resource.

If you can't use a more suitable element like button (as your example suggest), I would use event.preventDefault() to cancel the default behaviour.

like image 29
alex Avatar answered Oct 05 '22 09:10

alex