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

javascript - Empty URL hash causes page to jump on js events - Stack Overflow

programmeradmin0浏览0评论

I have a gallery of photos with a next and previous button. If one of my javascript methods is broken for one reason or another when one of the buttons is clicked it will add a hash to the url i.e. www.google# . I know the hash can be given a div id to jump to that part of the page but when it's blank it jumps around my page a few times and I'm not sure what it's targeting. I thought of attempting to remove the hash from the url but then I'd have to ensure that on every action and that seems like bad practice. I would prefer if the hash just made no difference to the actions on the page.

I have a gallery of photos with a next and previous button. If one of my javascript methods is broken for one reason or another when one of the buttons is clicked it will add a hash to the url i.e. www.google.# . I know the hash can be given a div id to jump to that part of the page but when it's blank it jumps around my page a few times and I'm not sure what it's targeting. I thought of attempting to remove the hash from the url but then I'd have to ensure that on every action and that seems like bad practice. I would prefer if the hash just made no difference to the actions on the page.

Share Improve this question asked Nov 1, 2013 at 13:46 JewrassicParkJewrassicPark 1891 gold badge2 silver badges12 bronze badges 3
  • 1 A 'blank hash' will usually take your browser window to the top of the page. – putvande Commented Nov 1, 2013 at 13:49
  • Have a read through this : stackoverflow./questions/1357118/… sounds like you need to prevent the default event. – Nick R Commented Nov 1, 2013 at 13:49
  • I'm aware of prevent default but if the hash in the anchor tag href is improper then that's easier to change then attaching handlers to prevent default for everything. My biggest problem is broken javascript so I don't wanna use js to solve it if I can avoid it. – JewrassicPark Commented Nov 1, 2013 at 13:59
Add a ment  | 

3 Answers 3

Reset to default 2

Don't use href="#", it is improper.

Instead, use href="javascript:;" or a variant thereof (personally I use javascript:void(null);)
This explicitly states that the link does not go to another location, but is handled by JavaScript.

I guess Next And Prev button has <a href="#" ...</a> like markup. In this case you can add event listener to those links with jquery

$('#prev, #next').on({
    'click': function(e) {
         e.preventDefault();
     }
})

and avoid changing location by browser. Or in pure javascript:

document.querySelectorAll('#prev, #next').addEventListener('click', function(e) {
    e.preventDefault();
},false)
//Note: this code is not cross-browser

Don't use an anchor tag when you don't want to perform a navigation function. Use button

发布评论

评论列表(0)

  1. 暂无评论