Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent scrolling to top when using jQuery .load

Tags:

jquery

I have three buttons on the site and when you click each one, they use .load to add different things to a DIV. The problem I'm having is whenever you click a button, it sends you back to the top of the page. I've tried using preventDefault() and return false but it didn't work for me, I might have just placed it in the wrong spot.

You can see the problem at http://coralspringshigh.org/cshs/ , here's the jQuery that I have now:

    if($(tabsId).length > 0){
            loadTab($(tabsId));
        }
        $(tabsId).click(function(){
            if($(this).hasClass(selected)){ return false; }
            $(tabsId).removeClass(selected);
            $(this).addClass(selected);
            $(containerId).hide();
                loadTab($(this));
            $(containerId).fadeIn();
            return false;
        });

    function loadTab(tabObj){
     if(!tabObj || !tabObj.length){ return; }
     $(containerId).addClass('loading');
     $(containerId).load(tabObj.attr('href'), function(){
          $(containerId).removeClass('loading');
          $(containerId).fadeIn('fast');
     });
    }

Thank you in advance.

like image 914
Koalatea Avatar asked Sep 24 '11 07:09

Koalatea


1 Answers

Your Issue

When you are loading the content, you are hiding the previous content, which is shortening your page. So, your page is not scrolling up, but your page is becoming shorter, and your browser is re-aligning to the new bottom of the page. This is what is causing the behavior you are seeing.

The Solution(s)

To solve this problem, there are a few things you can do. My recommendation is to load the content in the background, and display a loading overlay that goes over the old content. Then, when the new content is loaded, swap it out by hiding the old content after you show the new content. The user won't see a difference since it will happen quickly, but you not get that 'scroll' effect.

Another way to solve it is to use the jQuery .scrollTo() function to scroll to the new content after it is loaded, so that the content goes to the top of the page (or as high as the page can be).

Addendum

Your HTML is not completely valid. The <div> element cannot have an href attribute. Instead, wrap your text in an <a> tag to make it valid.

<div class="classname"><a href="page.html" class="ajaxclicklink">Students</a></div>

and from there, your code should do a

event.preventDefault();
event.stopPropagation();

This will stop the default linking, and also allow the use of a browser that does not support javascript. It is a good practice (and more symatically correct, imo) to have full working links instead of just javascript faked links.

like image 190
LoveAndCoding Avatar answered Sep 27 '22 20:09

LoveAndCoding