/blog/articles/

How to load a part of a page via ajax

I’m currently working on a small portfolio project where we want to have cool page transitions when the users goes from the homepage to a project single page without the classic reload which you normally get if you click on a link.

I tried to use smoothState.js which loads the content of the target page via ajax, keeps your sites urls intact and you don’t have much to do except load the script and add a few lines of Javascript.

It works fine but it’s not flexible enough for what we want to do so I set out to write the whole thing myself. I’m not especially experienced with Ajax but there’s always something you don’t know even if you work on stuff you know a lot about, so I just gave it a try.

var projectContainer = $('#js_project-container');

$('.js_load-project').on('click', function(ev) {
    var href = $(this).attr('href');

    /**
     * Prevent default link behaviour
     */
    ev.preventDefault();

    /**
     * Load the project, then initiate the slides
     */
    projectContainer.load(href, doTheSlides);
});

If the user clicks a link on the homepage I load the content of the target url with jQuery’s .load() method. I prevent the browser from following the link and atfer the load event has finished I call the doTheSlides function, which handles the animations.
After a few tests I was happy with the result besides that I loaded in the whole DOM including the complete section.

After a few Google searches I found out that you can target a specific id on the target page you want to load and only grab the content of that specific element. Perfect.

The updated code:

var projectContainer = $('#js_project-container');

$('.js_load-project').on('click', function(ev) {
    var href = $(this).attr('href')+' #project';

    /**
     * Prevent default link behaviour
     */
    ev.preventDefault();

    /**
     * Load the project, then initiate the slides
     */
    projectContainer.load(href, doTheSlides);
});

This will only load the contents from

from the project single page and inject them into the
on the homepage.

Make sure to add a space between the url you want to load and the target id. Otherwise it won't work.
And remember, the .load method only works with requests to the same domain, not cross-domain.

Of course this is only a small portion of the complete solution I need for the project I'm working on but I thought it's worth sharing. I hope somebody can make use of it.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.