41

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?

0

2 Answers 2

47

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:

jsfiddle

$(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.

Button styles example

1
  • OP mentions they want to use a button.
    – RobW
    Commented Mar 17, 2014 at 18:56
34
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
6
  • cant 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
    – John
    Commented Mar 1, 2013 at 13:35
  • hey, you have to replace $(element) with $("#goHere"). $("body") will remain as it is because we want to move scrollbar of body. Commented Mar 1, 2013 at 13:36
  • this code works great in chrome , but not in firefox, at least not in ff 21.0 :(
    – inadcod
    Commented May 28, 2013 at 8:15
  • 2
    the fix is to add $("body, html").scrollTop(...)
    – inadcod
    Commented May 28, 2013 at 8:24
  • I want to achieve this effect, but I'm a n00b. Where does this code go? Commented Feb 6, 2014 at 19:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.