In one of my projects, we wanted to use ‘Smooth sliders’ to transition the user from one anchor to another. One of my <a href=”#anchor” /> tags was inside a display template. I referenced JQuery and a custom .js file with $(document).ready to set up my smooth sliders. I ran into a weird issue that this would work for all ‘normal’ anchors, but not for the one that was included in my Display Template.
First, most examples I ran across on the internet used ‘body html’ to make the JQuery smooth sliding work. In SharePoint this will not work, because the body tag has the unfortunate attribute scroll=”no”, so all those examples won’t work. This post made me figure out you have to push the functionality to the s4-workspace div rather than the body. I used that post in combination with the library JQuery scrollTo to get things working for all my ‘normal’ anchors. Here’s how that works.
In the HTML, use the following <a href=”#topOfPage”>back to top</a> to define where you want to scroll to. Include a link to JQuery, JQuery scrollTo and a custom .js file like so:
And finally, in the referenced .js file, call the following code:
As noted above, this would work for all my anchors, except the ones in a Display Template. Unfortunatly, the Display Templates fully load in the DOM after $(document).ready fires, which means that my anchors were not yet getting picked up. To fix this, you have to include the same code in the html of your display template. Specifically, in the first <!–#_ section that you find, inside the first div underneath the body tag. What you have to add here is twofold, first include the link to the .JS file JQuery scrollTo, like so:
And after that, if you have already defined a function for ctx.OnPostRender, include the following code in that:
If you have not yet defined a function for ctx.OnPostRender, define it like this:
That’s it, the JQuery code will now also affect the anchors in your Display Template! Gotcha!