1

The following code is causing the page to scroll down to the bottom of the page. How do I prevent the page from scrolling in this situation?

// If note is clicked, then append id as hashtag at end of url
$("span.note").click(function(e){
    e.preventDefault();
    window.location.hash = $(this).attr('id');
});
Stephen305
  • 1,077
  • 3
  • 22
  • 30

2 Answers2

0

Additionally you could try to add: e.stopPropagation();

Stefan Pöltl
  • 362
  • 3
  • 9
0

To disable scroll without removing hash in window.location

You can temporarily remove id of your node before changing location.hash Then you set id again on node

// Prevent default on anchor link click
$("a[href^='#']").click(function(e) {
    e.preventDefault();
    changeHashWithoutScrolling($(this).attr('href'));
});

// Prevent instant scroll of browser
function changeHashWithoutScrolling(hash){
    if($(hash).length > 0){
        var $el = $(hash);
        var elId = $el.attr('id');
        $el.removeAttr('id');

        window.location.hash = hash;

        $el.attr('id', elId);
    }
}
Arthur Bouchard
  • 425
  • 6
  • 7