As the title says I want to make the page scroll to a specific element on the page when the user clicks a text/image. If it's possible, I don't want it to just skip to that element, but have a scrolling animation to it. I know it's possible to do in JS, but I forgot how you do it.
Asked
Active
Viewed 96 times
0
-
possible duplicate of [jQuery animate scroll](http://stackoverflow.com/questions/8047454/jquery-animate-scroll) – Blue May 31 '15 at 08:03
-
I found another post with similar question http://stackoverflow.com/questions/15664799/how-to-scroll-to-element-cross-browser-using-jquery-animate – B L Praveen May 31 '15 at 08:06
1 Answers
2
Depending on your specific needs you can organise the code in such way, so that you can pass the id of the element that needs to be scrolled to the click handler.
<a href="#scrollHere">Click me</a>
<div id="scrollHere"></div>
$('a[href^="#"]').on('click', function(event) {
var target = $(this.href);
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
});
This will scroll the page to #scrollHere
element over a period of one second (1,000 milliseconds = 1 second)
.
Or in a more generic way:
$('.someElement').on('click', function(event) {
var target = $('#someElementToScrollTo');
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
});

Slavenko Miljic
- 3,836
- 2
- 23
- 36