jQuery jump or scroll to certain position, div or target on the page from button onclick
184,078
Solution 1
I would style a link to look like a button, because that way there is a no-js fallback.
So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.
Original example:
$(document).ready(function() {
$(".jumper").on("click", function( e ) {
e.preventDefault();
$("body, html").animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
});
});
#long {
height: 500px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Links that trigger the jumping -->
<a class="jumper" href="#pliip">Pliip</a>
<a class="jumper" href="#ploop">Ploop</a>
<div id="long">...</div>
<!-- Landing elements -->
<div id="pliip">pliip</div>
<div id="ploop">ploop</div>
New example with actual button styles for the links, just to prove a point.
Everything is essentially the same, except that I changed the class .jumper
to .button
and I added css styling to make the links look like buttons.
Solution 2
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
Author by
John
Updated on August 16, 2020Comments
-
John over 3 years
When I click on a button i want to be able to jump down or scroll to a specific div or target on the page.
$('#clickMe').click(function() { //jump to certain position or div or #target on the page });
How can I do this?
-
John about 11 yearscant get that to work, where body is i have specified by div #goHere, i need it to scroll down the page to a specific div. cheers
-
Muhammad Talha Akbar about 11 yearshey, you have to replace
$(element)
with$("#goHere")
.$("body")
will remain as it is because we want to move scrollbar of body. -
inadcod almost 11 yearsthis code works great in chrome , but not in firefox, at least not in ff 21.0 :(
-
inadcod almost 11 yearsthe fix is to add
$("body, html").scrollTop(...)
-
CodyBugstein about 10 yearsI want to achieve this effect, but I'm a n00b. Where does this code go?
-
RobW about 10 yearsOP mentions they want to use a button.
-
Rajaraman almost 8 yearsit works for me thanks
-
bergie3000 almost 7 yearsnice one liner ... helps when using it in the console