Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to section in HTML/CSS

if I have the following JS code:

 //Scroll Down button
    $(window).scroll(function () {
    if ($(this).scrollDown() > 100) {
      $('.containerScroll').fadeIn('slow');
    } else {
      $('.containerScroll').fadeOut('slow');
    }
  });

  $('.containerScroll').click(function () {
    $('html, body').animate({
      scrollTop: 0
    }, 1500, 'easeInOutExpo');
    return false;
  });

This basically is for the Back-top-button animation where if the user clicks the button, then it brings the user back to the homepage with smooth scrolling. I would like the opposite. Is there a way to modify the above JS code so that when the user clicks the button, it brings the user to whichever page they desire? Right now, this scrolls all the way to the top and brings the user to only the homepage of the website, but how can I make it so it would bring the user to whichever page on the website?

This is what I have in HTML file:

<a href="#about" class="containerScroll">
      <div class="first-scroll"></div>
      <div class="second-scroll"></div>
      </a>

Basically, I would like the user to go in the about section of the page instead of the homepage. Any suggestions on how to achieve this task?


2 Answers

to top

window.scrollTo({
  top: 0,
  behavior: 'smooth'
});

to element

const element = getElementById("someElement");
//you can do it by jquery. no matter
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});

MDM: scrolIntoView

MDM: scrollTo

like image 79
Robert Avatar answered Apr 24 '26 07:04

Robert


You can set the scrollTop value to the offset of whatever element you want. For example:

$('html, body').scrollTop($('#about').offset().top);

will set scrollTop to the top of the element with id about by getting its offset.

Or you could use animate as you did in your example:

$('html, body').animate({
    'scrollTop': $('#about').offset().top
}, 1500);

Fiddle

Fiddle smooth scroll

like image 40
Matt Avatar answered Apr 24 '26 06:04

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!