[SalesForce] Scroll down automatically after clicking on CommandButton or we can say Pageblock refresh to a bottom of the page

Hi I have lengthy custom form, wher user can select some field, when he submit the another page block except this list of fields refreshes and shows the list of batch classes at bottom of the page.

but when the user submits, the pageblock gets refreshed and it go to the top of the page , but i want that to scroll down to the bottom of the page automatically where my another pageblock resides.

i found the snippet of java script function which works fine on page load, but i want it to happen conditionally on button click.

<script>
function Scrolldown() {
window.scroll(0,500);
}
window.onload = Scrolldown;
</script>

below is my command button

  <apex:commandButton value="  Submit  " action="{!docSubmit}" onclick="return confirmSubmit()" />

i added the oncomplete to my button and called the js function it didnt work.

Or any suggestion where i can do this with my Visualforce – attributes/Label/Goto like concepts or with my apex code.

Best Answer

<apex:commandButton 
    value="..." 
    action="..." 
    onclick="..." 
    reRender="someAreaById" 
    oncomplete="scrollSomewhere()" />

someAreaById should be the area to be refreshed; you can can give the form itself an Id and rerender the entire form. This is usually what I do if I can't readily determine which parts of the form may be affected. Other times, I can, and I rerender just a small part of the form. It will load much faster this way. scrollSomewhere() should be a function to write to scroll to a certain area. It could be window.scroll, or HTMLElement.scrollIntoView, which is supported on all modern browsers. You could query the element to scroll to by Id or some other attribute.

function scrollSomewhere() {
    document.querySelector('#someDiv').scrollIntoView();
}

If the element is a Visualforce element, the ID value will be modified, so you should use the $Component global variable to correctly identify the component, and you'll also need to escape the ":" with \3a for a proper match:

'#{!SUBSTITUTE($Component.form.block2.someElement,':','\\\\3a')}'

JavaScript requires \\ to represent a literal \, and the formula tool requires \\ to represent a literal \, so you end up double-escaping the \3a required by CSS.