Doubts with anchor link

2

I created a script as follows:

<script>
$(function() {
  $('#mostrar_planos').bind('click',function(event){
    var $anchor = $(this);
    $('html, body').stop().animate({scrollTop: $($anchor.attr('href')).offset().top}, 500,'swing');
  });
});
</script>

<a href="#mostrar_planos" id="mostrar_planos">Confira os planos</a>

<section id="mostrar_planos"> conteudo </section>

It works normally, but does not leave the ID that was called, in this case section , at the top of the screen.

It sits in the middle of the screen. Is there any way to tweak this?

I need when I click the link, it slides the page and leaves that section at the top of the page, not in the middle.

    
asked by anonymous 07.06.2018 / 15:48

1 answer

3

Your problem is that you are using the same ID link you are using in the content that you want to go to.

Note that your content does not have a ID equal, repeated, with the same name as the ID of the link: id="mostrar_planos" Just remove the link ID it resolves.

<a href="#mostrar_planos" id="mostrar_planos">Confira os planos</a>

<section id="mostrar_planos"> conteudo </section>

OBS: If there is no remaining content below the element that you anchor it the screen will stop uploading. See in the code below, I put an offset to the content for the 50px from the top, and below it a div with 500px in height. If you test in a small window it gets right. But if the window is more than 500px in height the element does not rise any more. Soon if in your case there is nothing else below the anchored element it goes to before the top.

See it working.

$('a.teste').on('click', function(e) {
    e.preventDefault();
    var id = $(this).attr('href'),
    targetOffset = $(id).offset().top;


    $('html, body').animate({ 
    scrollTop: targetOffset - 50 //altura que para antes do topo da tela
    }, 500,'swing');
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><aclass="teste" title="segmentos" href="#mostrar_planos">Confira os planos</a>
        
<DIV style="height: 200vh;"></DIV>

<section id="mostrar_planos"> conteudo </section>

<DIV style="height: 500px; background:tomato;"> div com 500px de altura</DIV>

        
    
07.06.2018 / 16:05