Scroll according to clicked element

Asked

Viewed 243 times

1

I have a list of links, example:

    <ul class="todos-links">
     <li> <a href="#alvo1"> Alvo1 </a> <li>
     <li> <a href="#alvo2"> Alvo2 </a> </li>
     <li> <a href="#alvo3"> Alvo3 </a> </li>
     <li> <a href="#alvo4"> Alvo4 </a> </li>
     <li> <a href="#alvo5"> Alvo5 </a> </li>
     <li> <a href="#alvo6"> Alvo6 </a> </li>
   </ul>

And down below, I have some elements, example:

<div id="alvo1">  eu sou o Alvo1 </div>
<div id="alvo2">  eu sou o Alvo2 </div>
<div id="alvo3">  eu sou o Alvo3 </div>
<div id="alvo4">  eu sou o Alvo4 </div>
<div id="alvo5">  eu sou o Alvo5 </div>
<div id="alvo6">  eu sou o Alvo6 </div>

The question is: How do I click on a link and carry out a scroll up to their respective alvo?

Example, click on the link Alvo1 and roll into the div id alvo1.

1 answer

2


You can do it like this:

$('[href^="#alvo"]').click(function(event) {
  event.preventDefault();
  let target = this.getAttribute("href")
  $('html, body').animate({ scrollTop: $(target).offset().top}, 1000);
});
div {
  margin-top: 500px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="todos-links">
 <li> <a href="#alvo1"> Alvo1 </a> </li>
 <li> <a href="#alvo2"> Alvo2 </a> </li>
 <li> <a href="#alvo3"> Alvo3 </a> </li>
 <li> <a href="#alvo4"> Alvo4 </a> </li>
 <li> <a href="#alvo5"> Alvo5 </a> </li>
 <li> <a href="#alvo6"> Alvo6 </a> </li>
</ul>


<div id="alvo1">  eu sou o Alvo1 </div>
<div id="alvo2">  eu sou o Alvo2 </div>
<div id="alvo3">  eu sou o Alvo3 </div>
<div id="alvo4">  eu sou o Alvo4 </div>
<div id="alvo5">  eu sou o Alvo5 </div>
<div id="alvo6">  eu sou o Alvo6 </div>

You can read more about jquery Animate here.

  • That’s exactly what I was doing this way, but with a different selector object in the event of click. Thank you!

Browser other questions tagged

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