jeancallisti
jeancallisti

Reputation: 1681

SharePoint 2016 on premise : how to scroll to top of the page?

My use case is very simple: I'm in a custom list form (modified NewForm.aspx, added with SharePoint Designer). I've added a button and I want that when the users clicks on it, the page scrolls back to the very top.

I've tried to following approach :

In the aspx

<button onclick="return MyScrollTop()">SCROLL TOP</button>

In the javascript

function MyScrollTop() {
    //All my attemps go here

    return false; 
}

I'm not detailing how I'm making sure that the function is called (it can be tricky sometimes in SharePoint, with the MDS and _spBodyOnLoadFunctionNames.push, but I'm 100% certain that my function is called as I see it in the browser's debugger.

I'm using IE11, both in "10" and "Edge" modes.

Here are my attempts (I tried them one by one, not in the same function)

//attempt #1 (as seen on W3C)
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;

//attempt #2 (as seen on Stack Overflow for regular javascript)
window.scrollTo(0,0);

//attempt #3 (as seen on Stack Overflow for some corner case - desperate attempt)
window.scroll(0,0);

//attempt #4 (as seen on Stack Overflow to fight SharePoint's '_maintainWorkspaceScrollPosition' hidden control on a page reload or unload)
var scrollX = document.getElementById('__SCROLLPOSITIONX');
var scrollY = document.getElementById('__SCROLLPOSITIONY');
if (scrollX && scrollY) {
    scrollX.value = 0;
    scrollY.value = 0;
}

var workspaceY = document.getElementById('_maintainWorkspaceScrollPosition');
if (workspaceY) {
    workspaceY.value = 0;
}

None of these work. When I click on the buttons, the breakpoints show me that my script is executed, but it's like window.scrollTo and others have no effect at all.

I've put a breakpoint in this SharePoint function from init.js to see if I can hook myself somewhere, but I'm not sure wht I should do :

if (!g_setScrollPos) {
    if (browseris.firefox && browseris.firefox36up)
        window.scrollTo(0, 0);
    if (Boolean((ajaxNavigate.get_search()).match(RegExp("[?&]IsDlg=1")))) {
        if (!isIE7 || elmWorkspace.scrollHeight < elmWorkspace.clientHeight)
            elmWorkspace.style.overflowY = "auto";
    }
    var scrollElem = document.getElementById("_maintainWorkspaceScrollPosition");

    if (scrollElem != null && scrollElem.value != null) {
        elmWorkspace.scrollTop = Number(scrollElem.value);
    }
    g_setScrollPos = true;
}
CallWorkspaceResizedEventHandlers();
g_frl = false;

Upvotes: 0

Views: 2480

Answers (1)

jeancallisti
jeancallisti

Reputation: 1681

I finally managed to do it like this :

var w = document.getElementById("s4-workspace");
w.scrollTop = 0;

Upvotes: 1

Related Questions