2714

I have this input element:

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

Then I have some other elements, like other tag's & <textarea> tag's, etc...

When the user clicks on the <input id="#subject">, the page should scroll to the page's last element, and it should do so 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.

3

33 Answers 33

1
2
2

jQuery(document).ready(function($) {
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash,
        $target = $(target);

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul role="tablist">
  <li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
  <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
  <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>

<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>

2

You just need:

$("selector").get(0).scrollTo(0, 0)
3
  • 1
    And you can use it with options to smooth the scroll with something like element.scrollTo({ top: 100, left: 100, behavior: 'smooth' }); See developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo Commented Aug 13, 2020 at 12:33
  • Please add some explanation to your answer such that others can learn from it.
    – Nico Haase
    Commented Aug 13, 2020 at 12:45
  • It's easy. "Inside" every jQuery object we have simple javascrip element. You can access it via .get method (api.jquery.com/get/#get-index) or simply by calling [0]: $("selector").get(0) of $("selector")[0]. You'll get JS element, like if you got it via document.getElementById("selector_id"). So you can call any JS function, like scrollTo or scrollIntoView. Commented Oct 12, 2020 at 11:04
0

Will do the trick, but will change your hash. If you use Jquery tabs and want page scrolls to tabs header you can:

$('#needed_tab').tab('show');
window.location.hash = '#tabs_block';
1
2

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