Scroll to a specific Element Using html
Is there a method in html which makes the webpage 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;
}
<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
You should mention whether you want it to smoothly scroll or simply jump to an element.
Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id
. A side effect is that #theID
will be appended to the URL
<a href="#scroll">Go to Title</a>
<div>
<h1 id="scroll">Title</h1>
</div>
You can add CSS effects to the target when the link is clicked with the CSS :target
selector.
With some basic JS you can do more, namely the method scrollIntoView()
. Your elements don't need an id, though it is still easier, e.g.
function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView();
// will scroll to 4th h3 element
}
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).
Year 2020. Now we have element.scrollIntoView()
method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
<a href="#id-of-element" class="smooth-goto">Text</a>