Id in url is not locating element in DOM on page load.
I am working on a server-side rendered app which uses a templating language to render HTML. Before submitting a form the user has the option go back and change one of their inputs. This is achieved by adding the ID ref that I want to scroll to the end of the href URL.
e.g. <a href="/form/edit#form-error>Change</a> would go to the /form/edit page and automatically scroll to the element with an ID of form-error.
This works perfectly well in Chrome and Edge. However, in Firefox the page simply renders in the centre. A page refresh does the same thing. However, if i click the url bar and press enter it scrolls to said element. I think Firefox maybe loads DOM elements, javascript etc in a different order is the issue? Any help with this much appreciated!
ప్రత్యుత్తరాలన్నీ (2)
Navigation to anchors is based on vertical distance from the top of the page. If the position of the element changes after Firefox initially computes it, Firefox usually ignores that later change. You can use a script to fix the position after load, for example:
var elId = window.location.hash; if (elId.length > 1){ el = document.getElementById(elId.substr(1)); el.scrollIntoView({block: "center"}); }
I guess the question is how/when to fire it. Does your application already have some code that runs on load or on pageshow?
Thanks jscher2000 for such a quick reply. Sadly I don’t think this will work for me. My app is rendered via a templating engine/node so window, document etc isn’t available to me. Also I can’t attach a script to the rendering file as it is a form page so would be vulnerable to XSS attacks.