Thursday, January 11, 2018

Creating anchor link scrolling on a modern page using the Modern Script Editor Web Part

There are times when you might have some topical links at the top of a page, and once clicked you want the page to scroll down to the right section. This is a perfect use-case for the Modern Script Editor web part. The Modern Script Editor web part is part of the PnP sample web parts project at Github. (A pull request with an updated version to SPFx v1.4 is in the progress of being processed.)

First add a text section, highlight the link part and in the address field type a hash sign and a unique name. In my case I use #scrolltome.

image

Below the hero web part I add an instance of the Modern Script Editor web part. And this is the easy part. Paste in either of the following HTML snippets and your page will scroll down to this place once the above link is clicked. In the old days anchor tags was used for this, but in these modern times any tag with a unique id works.

  • <a name="something"></a>
  • <span id="something"></span>

image

The updated script web part has an added property to remove the top/bottom padding of the container, thus making the web part take up zero real estate on the page, perfect for this case.

image

Once you save your page and test the link this is what it looks like:

scroll

If you want a more smooth scroll that’s also possible with your favorite smoothing scrolling script/css.