Reputation: 65
So I found this script by a user of this site however I can't remember the author. The script is working, however I want it to scroll more "smoothly" than just instantly appear at my desired information. And if possible, have the destination appear 300pixels above the div.
How do I do that?
#general{
margin-top:900px;
height: 100px;
weight: 100px;
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var hashTagActive = "";
$(".scroll").click(function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().center > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().center;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
</script>
<div>
<a class="scroll" href="#general">Hello</a>
</div>
<div id="general">
</div
Upvotes: 0
Views: 210
Reputation: 3243
How to animate to #id
links:
<a href="#content">Click me!</a><br>
<a href="google.com">Google.com</a>
<div id="content"></div>
#content {
margin-top: 900px;
height: 100px; width: 100px;
background-color: lightgreen;
}
$('a').on('click', function (event) {
var target = $(this.hash),
top;
if (target) {
top = target.offset().top;
event.preventDefault();
$('html, body').animate({
scrollTop: top
}, 600, 'swing');
}
});
Upvotes: 0
Reputation: 2117
For smooth scroll to 300px above top of the element, your JavaScript function should look like this :
$(".scroll").click(function (event) {
$('html,body').animate({
scrollTop: ($(this.hash).offset().top - 300)
}, 2000);
event.preventDefault();
});
Upvotes: 0
Reputation:
For a smoother scroll you can use:
$(document).ready(function() {
$("ANCHOR LINK").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
});
});
And you see the last number? 1000
, make it bigger to make it slower.
The second thing I'm afraid I can't help you with.
Upvotes: 1