1

/Editted//

I am trying to make my webapp have a nice loading animation between pages, and to quickly fetch them. It breaks the second time when I click a link. It feels as if the script only allows itself to be run on the original content, and not the newly loaded remote content. Or it might be that it only is working once, on the first link and back button. I can't figure it out.

////////////// Change page function ///////////////////
function changePage(href){
    $('div#pre-loader').removeClass('hide');
    $('.page-content').addClass('hide');
    var newHref = href.replace(site_url, site_url+'/data');
    $.get(newHref, function(data){
        $('div.page-content').replaceWith(data);
        $('div#pre-loader').addClass('hide');
    });
}

///////////Link click///////////
$('a').click(function(e){
    if (Modernizr.history){
        if($(this).hasClass("internal-link")){
            e.preventDefault();
            var href = $(this).attr("href");
            history.pushState(null, null, href);
            changePage(href);
        }
    }
});
//////////// Back button ////////////
window.addEventListener('popstate', function(event) {
    newHref = site_url + location.pathname;
    changePage(newHref);
});

When I add in the /data/ part to the url my server only returns what's inside the page-content div, and it isn't hidden anymore.

EDIT Realized the issue, it seems that the js which I have already loaded(in app.js, where the above code is) is not running on the newly loaded content. This would be because I leave all my CSS and JS files intact, and only load the content(with the extra /data/). Now I have tried googling and searching all through SO, and nowhere does it seem to address the issue. Is there any simple script which i can include in all the /data/ files which will reload the js, or is there a way in which i can make my scripts automatically run on new content?

4
  • See this question.
    – DCoder
    Jul 6, 2015 at 12:29
  • Changed code to this: pastebin.com/GuXRC4Nx and nothing has changed....
    – Irontiga
    Jul 6, 2015 at 12:53
  • You misunderstood the answer. The key point is that the answers in that question use three arguments for on, not two like your code does.
    – DCoder
    Jul 6, 2015 at 13:02
  • Thanks so much!! I didn't need 3 functions...all i needed to do was change $('a').on('click',function(e){}) to $(document).on('click', 'a', function(e){}
    – Irontiga
    Jul 6, 2015 at 13:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.