Wednesday, February 19, 2014

SharePoint 2013 Search Paging - Auto scroll to top

Quick Answer:

$(window).bind('hashchange', function() {
    document.getElementById("s4-workspace").scrollTop = 0;
});



My Adventure:

So it's not as easy as it seems to override the default behaviour of the paging control on a SP2013/o365 site without the use of deployed code.

  • The paging control itself has an 'onclick' attribute contains javascript similar to the following:
    $getClientControl(this).page(51);return Srch.U.cancelEvent(event);
  • As you can see, the second part of that code - the Srch.U.cancelEvent(event); - seems to prevent any other attached events from firing (I could be wrong here).  This stops me from just attaching an event using jQuery or anything else to scroll to the top of the page.
  • The paging control itself is regenerated on every page call, preventing me from simply modifying the 'onclick' attribute and removing the offending code so I can add my own click events.

So due to all of this I'm left with a few options:
  1. Find the display template which deals with the creation of the paging control and try to kill that cancelEvent() call.
  2. Try to find a way to get my attached event to fire before the 'onclick' attribute.
  3. Try something a bit different.
So I had a look into option 1, and came up blank.  I found the display template responsible for the paging control (Control_SearchResults.html), but I didn't want my change to affect ALL the search results paging controls, so I skipped that approach.

So step 2 seemed to be a bust as I couldn't find a way to beat the 'onclick' attribute - it seemed as steady as adding '!important' to an inline HTML style attribute.

And I finally cracked it with step 3 when I stumbled across a blog (couldn't find it again to reference) which mentioned that you can use the "$(window).bind('hashchange', functionName);" function to fire whenever the page contents change from an ajax call.  So rather than override or add to the click event, I just wait for the page to change due to a filter to be applied, or a page to be changed, and it'll jumped to the top.

Not the most elegant of solutions, and certainly won't cater to every need, but good enough for me for my scenario.