With pure Javascript, you can do it this way:
URL of the page:
meusite.com.br/#localdesejado
or
meusite.com.br/index.html#localdesejado
or
meusite.com.br/index.html?localdesejado
Script:
(function(){
url_ = location.href;
if(url_.match(/localdesejado/)){
setTimeout("window.scrollTo(0,document.body.scrollHeight/2)",1);
}
})();
The script checks whether the "localdesired" string passed in the URL (eg.: meusite.com.br/#localdesejado
) is present and does the scroll
halfway through the screen.
I used the parameter "desired location" just as an example. You can use the term you want in the script.
Why did I use setTimeout
?
Because some browsers (I don’t know if all, maybe all) automatically return the screen to the top after the window.scrollTo
. Using setTimeout
, even with a minimum value of 1
, this problem with the browser is skirted and the screen does not return to the top.