Scroll to a div using jquery
There is no .scrollTo()
method in jQuery, but there is a .scrollTop()
one. .scrollTop
expects a parameter, that is, the pixel value where the scrollbar should scroll to.
Example:
$(window).scrollTop(200);
will scroll the window (if there is enough content in it).
So you can get this desired value with .offset()
or .position()
.
Example:
$(window).scrollTop($('#contact').offset().top);
This should scroll the #contact
element into view.
The non-jQuery alternate method is .scrollIntoView()
. You can call that method on any DOM element
like:
$('#contact')[0].scrollIntoView(true);
true
indicates that the element is positioned at the top whereas false
would place it on the bottom of the view. The nice thing with the jQuery method is, you can even use it with fx functions
like .animate()
. So you might smooth scroll something.
Reference: .scrollTop(), .position(), .offset()
First, your code does not contain a contact
div, it has a contacts
div!
In sidebar you have contact
in the div at the bottom of the page you have contacts
. I removed the final s
for the code sample. (you also misspelled the projectslink
id in the sidebar).
Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } );
in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click()
.
Third, scrollTo
is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo()
without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.
Ok, now on to a solution.
The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:
// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
// Remove "link" from the ID
id = id.replace("link", "");
// Scroll
$('html,body').animate({
scrollTop: $("#" + id).offset().top
}, 'slow');
}
$("#sidebar > ul > li > a").click(function(e) {
// Prevent a page reload when a link is pressed
e.preventDefault();
// Call the scroll function
goToByScroll(this.id);
});
Live Example
( Scroll to function taken from here )
PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a>
... <a name="gohere">blah title</a>
you can try :
$("#MediaPlayer").ready(function(){
$("html, body").delay(2000).animate({
scrollTop: $('#MediaPlayer').offset().top
}, 2000);
});