How to create link with scroll to page destination

0

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

    
asked by anonymous 01.11.2017 / 19:00

3 answers

2

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

www.youtube.com/video1?scroll=true

In the video1 section check whether GET['scroll'] == 'true' , if any, of 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 from the screen and divides by two, to pass as a parameter in the scrollTop method, so it will go down to the middle of the page.

If you want a solution only in javascript , you'll have to call localStorage or even SPA´s .

    
01.11.2017 / 19:30
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;
}

See this example here > Codepen - OnClick Scroll page Javascript & Jquery

    
01.11.2017 / 20:47
0

With pure JavaScript, you can do this:

Page URL:

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 to see if the "localhost" string passed in the URL (eg, meusite.com.br/#localdesejado ) is present and scroll to half the screen.

I used the " localhost " parameter as an example only. You can use the term you want in the script.

Why did I use setTimeout ?

Because some browsers (do not know if everyone, maybe all) will automatically return to the top after window.scrollTo . Using setTimeout , even with a minimum value of 1 , this problem with the browser is bypassed and the screen does not return to the top.

    
01.11.2017 / 20:35