stop scrolling to top after AJAX request

33,692

Solution 1

you should add return false to the end of your ajax call function. Or to the end of your inline call:

<a href="#" onclick="someAjaxCall(); return false">Link</a>

Solution 2

if you are calling the ajax via anchor click, try this:

<a id="clicker" href="#">Click here to do ajax</a>

$('#clicker').click(function(e) { e.preventDefault(); $.get("/myurl/") })

Solution 3

Attach the event handler with jQuery (not with the onclick attribute) and remove the href attribute altogether. The problem is that the browser is navigating when the link is clicked. I see this happen alot when onclick is used and there is an error in your event handler before preventing the default.

Another way to fix it for sure is to not use an <a> but rather a <span>.

Solution 4

/* AJAX stuff here */
$('html, body').stop();
Share:
33,692
Miroo
Author by

Miroo

Updated on March 16, 2020

Comments

  • Miroo
    Miroo about 4 years

    Possible Duplicate:
    How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript?

    my browser scrolls to top after ajax request then i use

     $('html, body').animate({ scrollTop: $('#loadMore').offset().top }, 2000);
    

    to scroll back to my div. is there a way i stop it from scrolling to top from the beginning

  • Miroo
    Miroo about 13 years
    the request adds # to my URL, why?!!
  • Miroo
    Miroo about 13 years
    the request adds # to the URL, that cause the scrolling to top
  • fl00r
    fl00r about 13 years
    you set it as href attribute to your link or it is default behavior. Show your code to understand what is going on.
  • fl00r
    fl00r about 13 years
    you should return false to prevent scrolling.
  • Miroo
    Miroo about 13 years
    it doesn't work after using return false :S
  • fl00r
    fl00r about 13 years
    It works if you put it in right place. But no one see your code and no one can say where did you put return false
  • Amy Anuszewski
    Amy Anuszewski about 13 years
    If you don't want the # appended, you can use a span instead of an href and attach the onclick to the span. That's how we do it in our applications that are negatively affected by the # in the url.
  • Miroo
    Miroo about 13 years
    @fl00r hey man thanx allot :) it helped like a charm :D i am done with today's tasks then ;)
  • mkk
    mkk about 12 years
    come on.. just remove # and that's it... (it should look like href="")
  • Paul Preibisch
    Paul Preibisch about 10 years
    I tried adding return false to all my ajax, but it never worked. Instead, I changed all <a> to <span> because "#" is causing browser to jump to the top as mentioned by user Miroo below
  • Jonathan Laliberte
    Jonathan Laliberte almost 7 years
    Changing the 'a' to a 'span' worked. Thanks @AmyAnuszewski