Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to an element with jQuery

I have this input element:

<input type="text" class="textfield" value="" id="subject" name="subject"> 

Then I have some other elements, like other text inputs, textareas, etc.

When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The last item of the page is a submit button with #submit:

<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done."> 

The animation should not be too fast and should be fluid.

I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.

like image 502
DiegoP. Avatar asked Jul 13 '11 09:07

DiegoP.


People also ask

How do I scroll to 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 can use scroll event in jQuery?

jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

How do I horizontally scroll a div using jQuery?

In jQuery, we can make any element tag move horizontally using the built-in function scrollLeft() function for scrolling the scrollbar horizontally according to either the position which is set as the parameter or without setting the position which would specify the position in pixel number of the scrollbar.


1 Answers

Assuming you have a button with the id button, try this example:

$("#button").click(function() {     $([document.documentElement, document.body]).animate({         scrollTop: $("#elementtoScrollToID").offset().top     }, 2000); }); 

I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.

<html>     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>     <script>         $(document).ready(function (){             $("#click").click(function (){                 $('html, body').animate({                     scrollTop: $("#div1").offset().top                 }, 2000);             });         });     </script>     <div id="div1" style="height: 1000px; width 100px">         Test     </div>     <br/>     <div id="div2" style="height: 1000px; width 100px">         Test 2     </div>     <button id="click">Click me</button> </html>
like image 161
Steve Avatar answered Oct 12 '22 20:10

Steve