JQuery – How to scroll an anchor to the top of the page when clicked

jqueryscroll

I have a list of links in div elements and I am using dropcontent.js to load content into another div when a link is clicked. I would now like to add some code which scrolls the clicked link to the top of the browser window.

HTML is like this for each item in the list:

<div class="work">
    <h3><a class="scroll" href="project2.html">Project 2</a></h3>
    <div class="projectIntro">
        <p>This is some intro text for project 2</p>
    </div>
    <div class="pictures"></div>
</div>

I have found tutorials for scrolling to an ID when a link is clicked (by making the href the ID of the div you want to scroll to – unfortunately I can't do this as my href is actually a separate html page even though it is using dropcontent to load it into the current page.

I also found a tutorial for scrolling to a particular ID on page load, but none that simply say when an anchor of a given class is clicked, scroll it to the top of the browser window.

Can someone help me out with this one please? thanks.

UPDATE:

I have got the scroll working using the following code:

$('.work a').click(function() {
         $('html,body').animate({scrollTop: $(this).offset().top}, 500);
         }); 

However, my dropcontent.js is no longer working… I think because I have 2 functions occuring on the same click… I would like the content to load first, then scroll.

here is my dropcontent.js

$('.work a').click(function(event) {
event.preventDefault();

var parent = $(this).parents(".work");
var content_holder = parent.children(".pictures");

if (parent.hasClass("selected_work")) {
  close_other();
  return;
}

close_other();

parent.addClass("selected_work");
content_holder.load(this + " #content .work");

$('.selected_work img').attr("src", "images/arrow_close.gif");

});


function close_other() {

var selected_work = $('.selected_work');

selected_work.children('.pictures').empty();    
$('.selected_work img').attr("src", "images/arrow_open.gif");
selected_work.removeClass("selected_work")
}

});

So now I just need to integrate these 2 bits of code to get them working together… so far no I have had no luck doing this – if I add the scroll (animate) function, the load function stops working…

UPDATE 2

Turns out it was something else which was causing the problem – I now have it working!

Best Answer

Here is how you scroll the link to the top:

$('.work a').click(function() {
     $('html,body').animate({scrollTop: $(this).offset().top}, 500);
});