最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The return false onclick anchor not completely working - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 13, 2011 at 5:07 RonnieTRonnieT 2,2034 gold badges33 silver badges44 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

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.

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.

发布评论

评论列表(0)

  1. 暂无评论