Reputation: 2876
I have an html page and I want to make it scroll slowly to a specific point or all around the page. I tried the following codes but nothing worked:
<a href="#anchorName"></a>
<script>
function scrollTo(hash)
{
location.hash = "#anchorName";
}
</script>
Secondly, I tried scrolling to a div but in this case I also had to use CSS and put a height. I am trying to avoid that.
As seen on stackoverflow past issues :
<a href="#myDiv" id="button">button</a>
<script>
$("#button").click(function()
{
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
</script>
and it did not work at all.
Upvotes: 1
Views: 6723
Reputation: 11
If you are using a css file the following rule can be inserted for a slow scroll ...
html {
scroll-behavior: smooth;
}
Upvotes: 1
Reputation: 1659
you can do a Smooth scroll to some component id by following the example codes using jQuery, for example :
<a class="move_to_div" href="#anchorName"> move div </a>
<div id="anchorName"> </div>
<script>
$(".move_to_div").click(function() {
$('html, body').animate({
scrollTop: $("#anchorName").offset().top
}, 1000);
});
</script>
this is just example , when click on 'a href link' the scrolldown will be smooth (to test the result add some space between a link and div by using css ) i hop this helpful for you .
Upvotes: -1
Reputation: 46
Try like this :
$(document).ready(function(){
$("#button").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 2000);
});
});
#myDiv {
margin-top: 800px;
height: 50px;
width: 300px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#myDiv" id="button">button</a>
<div id="myDiv"></div>
Upvotes: 3
Reputation: 1575
Since you are setting #myDiv
as href for the button, you have to preventDefault() before you trigger the animation:
$("#button").click(function(e){
e.preventDefault();
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="myDiv" id="button">button</a>
<div style="height:400px;"></div>
<div id="myDiv">Lorem Ipsum</div>
Upvotes: 1