tags:

views:

970

answers:

3

Hi,

I have a MVC app and using JQuery.

I have anchor that I setup like this

<a href="#" id="addcomment">Add Comment</a>

then when the anchor is clicked I do this

$('#addcomment').click(function() {
    $('#divComments').slideDown(2000);
});

Problem is when the anchor is clicked the browser scrolls to top of window immediately the link is clicked and then the div scrolls

How do I stop that happening??

Malcolm

+3  A: 

You have to add return false; at the bottom of your click function to prevent the default link event action from happening. The default link event in this case would be going to the top of the page because the href of # tells the browser to go to the top. So it would look like this:

$('#addcomment').click(function() {
    $('#divComments').slideDown(2000);
    return false;
});

While this is acceptable too:

$('#addcomment').click(function(e) {
    $('#divComments').slideDown(2000);
    e.preventDefault();
});

Documentation here.

Paolo Bergantino
+3  A: 

What's wrong with using a named anchor?

No need for the overhead of javascript.

Charlie Somerville
I agree. Why not just the tag and have to maintain extra script?
David Robbins
A: 

Thank you Paolo Bergantino, that was very helpfull, I was looking for this quite a long time today. Cheers!