Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery jump or scroll to certain position, div or target on the page from button onclick [duplicate]

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?

like image 355
John Avatar asked Mar 01 '13 13:03

John


People also ask

How do I scroll a specific div?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.

How do I scroll to a specific position?

Scroll to Specific Position in JavaScriptscrollTo( value-x, value-y ); Here value-x is the pixel value of the width, where you wanna jump or scroll to. value-y is for the height of the window in terms of the pixel where you wanna jump or scroll to. Let's just understand it with an example.

What is $( window scrollTop ()?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.


1 Answers

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

like image 158
Joonas Avatar answered Sep 22 '22 13:09

Joonas