Malcolm
Malcolm

Reputation: 12864

HTML Scroll position when anchor clicked

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

Upvotes: 0

Views: 2725

Answers (2)

user47322
user47322

Reputation:

What's wrong with using a named anchor?

No need for the overhead of javascript.

Upvotes: 3

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

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.

Upvotes: 2

Related Questions