Get Certified on your expert knowledge

Brainbench grant you full access to assessments and certifications covering over 600 skills in demand for today's marketplace.
Visit the site and get certified. Click Here to take some FREE tests.

Tuesday, May 29, 2012

Scrolling to div smoothly using Jquery

Want to navigate to particular div / portion of html in the same page?
There are three ways to do this :-
  1. Using anchor tag 
  2. Using pure Javascript.
  3. Using JQuery Scrolltop function.
Using anchor tag
This is the native method, giving id to the element that needs to be focussed and in href of anchor tag calling the id with hash.
eg: <a href="#abc">scrolltop</a>
This will jump to that element directly.

Using pure Javascript. 
Below is the function that will navigate to whichever element you want.
FUNCTION:
function scrolltoDiv(_id)
{
document.getElementById(_id).scrollIntoView(true);
}

CALLING THE ABOVE FUNCTION :-
You can call the above functions in following ways:
  1. <a href="javascript:scrolltoDiv('abc')">scroll top </a>
  2. <p onclick="scrolltoDiv('abc')">scrolltop</p>
  * where abc is the id of the element.

Using JQuery Scrolltop function.
Below is the function that will navigate to whichever element you want.
FUNCTION : 
function scrolltoDiv(_id)
{
    $('html, body').animate({
            scrollTop: $("#" + _id).offset().top
    },1000,'easeInOutCirc');
}    

CALLING THE ABOVE FUNCTION :-
You can call the above functions in following ways:
  1. <a href="javascript:scrolltoDiv('abc')">scroll top </a>
  2. <p onclick="scrolltoDiv('abc')">scrolltop</p>
  * where abc is the id of the element.

No comments:

Post a Comment