Call a Section tag without displaying the ID in the URL

Asked

Viewed 149 times

0

I wonder if there’s a way I could call one id of a Section HTML without displaying for example in the URL a #id, follows a print below to help in understanding

inserir a descrição da imagem aqui

I’d like to call the tag Section Sobre through a button or a tag <a> without displaying in the URL the #sobre, this is possible?

Section code

<a href="#sobre">Sobre</a>

<section id="sobre">
  <!-- Conteudo da section... -->
</section>

1 answer

3


With jQuery is possible using preventDefault() and .animate. The preventDefault() will prevent the link from changing the page URL, because it cancels the link event.

$(function(){
   
   $("[href^='#']").click(function(e){
      
      e.preventDefault();
      
      // pega o href que é o id da section
      var id = $(this).attr("href");
      
      $('html').animate({scrollTop: $(id).offset().top})
   });
   
});
section{
   margin: 500px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#sobre">Sobre</a>

<section id="sobre">
  section
</section>

The selector "[href^='#']" will fetch the elements where the attribute href begins with #.

With pure JS:

Can use .scrollIntoView():

document.addEventListener("DOMContentLoaded", function(){
   
   var ancoras = document.querySelectorAll("[href^='#']");
   
   for(var x=0; x<ancoras.length; x++){
      
      ancoras[x].onclick = function(e){
         
         e.preventDefault();

         // pega o href que é o id da section
         var id = this.getAttribute("href");
         
         document.querySelector(id).scrollIntoView({block: 'start', behavior: 'smooth'});

      }
      
   }
  
});
section{
   margin: 500px 0;
}
<a href="#sobre">Sobre</a>

<section id="sobre">
  section
</section>

The options of .scrollIntoView():

block: 'start': scroll goes to the beginning of the element. behavior: 'smooth': the scroll goes smoothly.

Browser other questions tagged

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