The code provided below is based entirely on this link, which proposes a way to scroll the view of the browser to the position of an element. It contains some minor tweaks to suit the question that was askek. I also extensively commented the code, since the link lacks severely in explaination.
// jQuery.fn is shorthand for jQuery.prototype and allows
// for the extension of the jQuery function set with
// custom functions.
// See: http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean
jQuery.fn.scrollView = function() {
return this.each(function() {
// This gives us the amount of pixels that is between
// the element and the top of the window.
var margin_top = jQuery(this).offset().top
// Here you can define an offset that leaves some space at the top
// of the element
var offset = 10px;
// Calling .animate() on the body and html objects
// makes the transition of these elements smooth (the duration
// of the transition is provided in the second argument in ms)
jQuery('html, body').animate({
// Setting the scrollTop property makes the page scroll
// upwards by the specified amount pixels.
// Setting scrollTop to margin_top makes the page scroll up
// the exact amount of pixels to make the element appear
// at the top of the window.
scrollTop: margin_top + offset
}, 200);
});
}
After adding this function to the jQuery prototype, you can now call it on any element you want.
// Calling scrollView on the selected element(s) calls the function
// we defined above and makes the page scroll so that that element
// is now at the top (with an optional offset)
jQuery('#my-element').scrollView();
Finally, this is how you would add it as an onClick event to your element:
// Bind an onClick event listener to all elements with the 'expand' class
jQuery('.expand').click(function(event) {
// Optionally you can use preventDefault() if it fits your needs
event.preventDefault();
// Call the scrollView function on the clicked element
jQuery(this).scrollView();
});