user1715025
user1715025

Reputation: 53

ajax call resetting window scroll position

I added a simple voting feature to my website. For some reason, the ajax call resets the window scroll to the top of the page. This is obviously very annoying for the user as they have to start scrolling from the top each time they vote on a post.

I can't seem to understand why it's happening. Any suggestions?

function vote_up(post_id)
{
  //alert("Up: " + post_id);
  $.ajax({
  url: '<?php echo URL::base(); ?>voting_ajax.php?vote_up&post_id=' + post_id,
  dataType: 'json',
  success: function(data) {
      if(data.result == 1)
      {
        $('#up_count_'+post_id).html(data.vote_up);
        $('#down_count_'+post_id).html(data.vote_down);
      }
      if(data.msg != '')
      {
    $.msgbox(data.msg);
      }
    }
  });

}

Upvotes: 1

Views: 543

Answers (2)

Josh Bedo
Josh Bedo

Reputation: 3462

You can do what @lkrups is saying or add event.preventDefault(); even adding return false; at the end of your function should work.

Upvotes: 2

Lkrups
Lkrups

Reputation: 1344

Do you have an empty 'href' or hash sign in your a tag such as

<a href="#" onclick="action();">vote me up</a> ?

If it is the case, the hash sign is what is scrolling up back to the top. You should use instead

<a href="javascript:void(0);" onclick="action();">vote me up</a>

Or have an event handler wich returns false as the default action.

Upvotes: 4

Related Questions