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.

4 comments:

  1. It looks good but I have no clue how to implement this via the instructions.

    ReplyDelete
  2. I agree! I have followed the directions on https://github.com/SharePoint/sp-dev-fx-webparts/blob/master/README.md. Updated CDN Path found in https://github.com/SharePoint/sp-dev-fx-webparts/blob/master/samples/react-script-editor/README.md and not able to upload.

    Is this still in test mode?
    Is this why there is not a *.sppkg file?

    ReplyDelete
    Replies
    1. A very good reason as you shouldn't really use script ed wp's :-) The latest version does not need CDN changes, but it won't work on a non-script site unless you change a config. I might build packages with an explanation in the future.

      Delete
  3. This was perfect! Got me exactly to the solution I needed very quickly. This literally made my vision for the content of my site possible. I was about to have to change my entire design based on the anchor limitation.

    ReplyDelete