Search code examples
javascriptjquerypage-fragments

Use jQuery's .load() to load page fragments but replaces everything in body


I want to replace the original div.wrapcontent with the contents of a fragment. But using .load replaces everything in the body, not just the specific div.

        $("nav#category-nav>ul>li").on("click", "a", function() {
        var $thecontent = $("#thecontent"),
        $wrapcontent = $("#thecontent > .wrapcontent");

        var path = $(this).attr("href");

        $wrapcontent.load(path);
    });

Solution

  • The problem stems from the default behavior of an anchor tag. By default, anchor tags redirect to their href. For your use case, you have to capture this default behavior and prevent it from occuring.

    Add the evt object to the function and prevent the default behavior like so:

    $("nav#category-nav>ul>li").on("click", "a", function (evt) {
        evt.preventDefault();
        var $thecontent = $("#thecontent"),
            $wrapcontent = $("#thecontent > .wrapcontent");
    
        var path = $(this).attr("href");
    
        $wrapcontent.load(path);
    });