How to create scroll link to target page

Asked

Viewed 872 times

0

Hello, I would like to know how I can link to my video page that scrolls down, but this page does not contain any id to use in the mode: <a href="linkdapagina#localdesejado">. Is there another way? For example, this link opens the page and then scrolls down 50%?

3 answers

2

If you are using PHP, can pass a parameter in the link, similar to

www.seusite.com.br/video1? scroll=true

In section video1 check if GET['scroll'] == 'true', if so, from a print in the following javascript function (ignore the rest)

var metadeDaTela = $(window).height() / 2;

var body = $("html, body");
body.stop().animate({scrollTop:metadeDaTela}, 500, 'swing');
  
body{
  height: 200vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>

</body>

In the function it takes the amount of pixels of the screen and divides by two, to pass as parameter in the method scrollTop, so it will go down to the half of the page.

If you want a solution on javascript, will have to appeal to localStorage or even SPA´s.

0

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.

0

The best way to do this is with Javascript and Jquery with the following function.

Remember to import Jquery into the head of your html, if it is not already added import it with:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>

JS:

$("button").click(function() {
    $('html,body').animate({
        scrollTop: $(".segundo").offset().top},
        'slow');
});

HTML:

<div class="primeiro"><button type="button">Mostra efeito</button></div>
<div class="segundo">Efeito de Scroll</div>

CSS:

.primeiro {
    width: 100%;
    height: 1000px;
    background: #ccc;
}

.segundo {
    width: 100%;
    height: 1000px;
    background: #999;
}

Take this example here > Codepen - Onclick Scroll page Javascript & Jquery

Browser other questions tagged

You are not signed in. Login or sign up in order to post.