0

Gostaria de saber se existe uma forma de eu chamar um id de uma section HTML sem exibir por exemplo na URL um #id, segue uma print abaixo para ajudar no entendimento

inserir a descrição da imagem aqui

Gostaria de chamar a tag section Sobre através de um button ou uma tag <a> sem exibir na URL o #sobre, isso é possível?

Código da Section

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

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

0

1 Resposta 1

3

Com jQuery é possível usando preventDefault() e .animate. O preventDefault() irá evitar que o link altere a URL da página, porque ele cancela o evento do link.

$(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>

O seletor "[href^='#']" irá buscar os elementos onde o atributo href inicia-se com #.

Com JS puro:

Pode usar .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>

As opções do .scrollIntoView():

block: 'start': o scroll vai ao início do elemento. behavior: 'smooth': o scroll vai de forma suave.

1

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .