8

I've created a Publishing page and added contents and Bookmarks (Anchors). I've tried to add smooth scrolling using jquery but it doesn't work. I want to be able to scroll to ANY anchor on the page.

I added an HTML form web part at the top of the page using SP UI. Added code from https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor

$('a[href*=#]').click(function () {
var hash = $(this).attr('href');
hash = hash.slice(hash.indexOf('#') + 1);
$.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
window.location.hash = '#' + hash;
return false;
});

Does anyone have any ideas why it's failing? Has anyone got this to work in SharePoint?

Thanks

1
  • I am struggling with the implementation of the same thing on my publishing wiki page. My links are in the form of Summary Links that are anchored to bookmarks within the same page. I would like to have it such that on clicking a particular summary link, it scrolls down smoothly to the anchor point. Thanks a lot! Sep 5, 2016 at 7:03

2 Answers 2

2

In Sharepoint 2013 and 2016 almost all the contents are inside the s4-workspace. So every calculation must include it. I've done it in this way (starting from the same example.

$(".scroll").click(function(event){
    event.preventDefault();
    // calculate destination place
    var dest = 0;
    var docH = $('#s4-workspace')[0].scrollHeight;
    var winH = $('#s4-workspace').height();
    if($(this.hash).offset().top > docH-winH){
        dest = docH-winH;
    } else {
        dest = $('#s4-workspace').scrollTop()+$(this.hash).offset().top;
    }
    //go to destination
    $('#s4-workspace').animate({scrollTop:dest}, 1000,'swing');
});

The links are required to be:

<a href='#anchor1' class='scroll' />
<a href='#anchor2' class='scroll' />

<a id='anchor1' href='#' />
text...
<a id='anchor2' href='#' />
text...
0

Thank you for this Piero! I've been bashing my head against the keyboard for over a day on this.

My code was:

$("a[href^='#']").click(function(e) {
  e.preventDefault();
  var position = $($(this).attr("href")).offset().top;
  $("#s4-workspace").animate({ scrollTop: position }, 600 );
});

It worked once, but if you didn't reset to the top of the page, the second, third, etc. link would go to some random spot. I'm not sure how your calculation differs, but it fixes the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.