yeppe yeppe - 2 months ago 6
jQuery Question

Why scroll top is needed after action submit for Struts2

Why screen scrolls down when page is rendered by struts2 action (Context: response from the server, equivalent jsp page rendered from sturts action).

This question has a reference to question asked here. http://stackoverflow.com/a/8181413/5086633

Here the solution given is to use this function

document.getElementById("idofyourdivhere").scrollIntoView(true);


However, for me the generated html page has lot of top level div which cannot be picked as explained above. I am left with this option to scroll to the top of the page (scroll top) after the page gets rendered. I just want to get rid of both, is there anyway to stop doing that and fix the same in the struts2 action/configuration itself ? I am preferably looking for a struts2 fix for this.

Answer

If you perform a standard submit, and you land in the middle of the page, it means that in your URL you have something like:

www.blabla.com/foo/bar#someID

, where #someID tells the browser to look for an object with id="someID" and scroll to it.

This mechanism can be originated

  • server side, by returning an URL with the fragment at the end, or
  • client side, with a javascript block executed on document ready, most likely through the usage of HTML5 replaceState() / pushState() APIs...

The cleanest solution is to remove this unwanted behavior at the source but, if for some reason you can't, you can do it client side like follows:

$(function(){ // On document ready...
   history.replaceState("","",location.href.substring(0,location.href.indexOf("#")));
    // ... remove all the URL portion following the # 
});

This will turn

www.blabla.com/foo/bar#someID

into

www.blabla.com/foo/bar

dynamically.