toll free: (866) 611-9441

jQuery scrollIntoView In One Line of JavaScript

Hi guys,

I was looking for a simple solution to scroll the page so the next mandatory field will become visible in case the user forgot to enter all the required data.
This very simple solution seems to work fine in FF3 and IE7:

$(‘html,body’).animate({scrollTop: $([selector]).offset().top-[offsettop]},500);

where [selector] represents your selector for the next mandatory field; for instance mine is “$(‘span:visible.pinpoint’).eq(0)”; that means the first span element that has the pinpoint class and is visible; that mean upon form submission I will check all the required fields and add the “pinpoint” class to them if they are empty.
[offsettop] is the offset you might want to apply so the element will not be positioned right at the beginning.

Give it a try and if you encounter difficulties I will post the actual page.

OK, here’s an example: scrollIntoView demo. Enjoy!

Tags: , ,

6 Responses to “jQuery scrollIntoView In One Line of JavaScript”

  1. Aaron says:

    Do you mind post the actual page? thx!!!

  2. Dragos says:

    I will make a simpler version and I’ll post it soon.

  3. Dragos says:

    Hi Aaron,

    Posted a .zip with a small demo. The page has bogus content, please disregard. I placed a link at the beginning that will trigger a show and a scroll to the text field (virtually required :) ). Of course, you will have to take care of the validation part and find your first invalid field. Take care…

  4. awesome thanks for this.

  5. david weisz says:

    whatever happened to the native javascript scrollIntoView method

    document.getElementById(‘myId’).scrollIntoView(true);

  6. luinloki says:

    Thanks for the post, it works perfectly!

Leave a Reply