HTML/CSS Buttons That Scroll Down to Different Div Sections on a Webpage

html/css buttons that scroll down to different div sections on a webpage

For something really basic use this:

<a href="#middle">Go To Middle</a>

Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.

How to make a button scroll down page in HTML?

Update: There is now a better way to use this, using the HTML id attribute:

Set the destination id: <h1 id="section1">Section 1</h1>

And create a link to that destination using the anchor tag: <a href="#section1">Go to section 1</a>

The benefit of this new method is that the id attribute can be set on any HTML element. You don't have to wrap superfluous anchor tags around destination links anymore!

Original answer:

You can look at using the HTML anchor tag.

<a name="section1">Section 1</a>

alongside

<a href="#section1">Go to section 1</a>

When the user clicks on "Go to section 1", they will be sent to the section of the page where the "Section 1" text is displayed.

Is there a way to link my menu buttons so I can scroll to diffrent parts on the same webpage?

<a href='#random'>Go</a>
<div id='random'>Hello</div>

Now when you click on the 'a' tag it will drop down to the div of id='random'

Scroll to a specific Element Using html

Yes you use this

<a href="#google"></a>

<div id="google"></div>

But this does not create a smooth scroll just so you know.

You can also add in your CSS

html {
scroll-behavior: smooth;
}

Scrolling anchor to sections

you need to leave some space at top equal to anchor-container's height
here i take innerHeight of anchor-container to take space including padding, see here

 $(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
var topmenu = $(this).parent('.anchor-container').innerHeight()
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - topmenu
}, 500);
});

One out of 2 buttons initiate scroll but both of them are supposed to

I think this would be better if you didn't use Javascript as some users disable it entirely when visiting websites.

Wrap an <a> tag around your buttons and use the href attribute instead.

section {
height: 70vh;
border: 1px solid black;
}
<section id="first-section">
<a href="#second-section"><button>Go to second section</button></a>
</section>
<section id="second-section">
<a href="#first-section"><button>Go to first section</button></a>
</section>


Related Topics



Leave a reply



Submit