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;
}
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).
<!-- 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.
By using an href attribute inside an anchor tag you can scroll the page to a specific element using a #
in front of the elements id name.
Also, here is some jQuery/JS that will accomplish putting variables into a div.
<html>
<body>
Click <a href="#myContent">here</a> to scroll to the myContent section.
<div id="myContent">
...
</div>
<script>
var myClassName = "foo";
$(function() {
$("#myContent").addClass(myClassName);
});
</script>
</body>
<nav>
<a href="#section1">1</a>
<a href="#section2">2</a>
<a href="#section3">3</a>
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
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>