user17458330
user17458330

Reputation:

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?

Upvotes: 3

Views: 13782

Answers (2)

Matt
Matt

Reputation: 2213

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

Upvotes: 3

Robert
Robert

Reputation: 2763

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

Upvotes: 3

Related Questions