Js not working

I have a script (from https://css-tricks.com/rethinking-dynamic-page-replacing-content/) to load content into a page without refreshing the entire page… works fine in non-WP sites but not in WP - where it seems to reload the entire page.

My knowledge of this stuff is extremely limited, so please excuse my ineptness.

Here’s the script:



$(function() {

    if(Modernizr.history){

    var newHash      = "",
        $mainContent = $("#main"),
        $pageWrap    = $("#wrapper"),
        baseHeight   = 0,
        $el;

    $pageWrap.height($pageWrap.height());
    baseHeight = $pageWrap.height() - $mainContent.height();

    $("nav").delegate("a", "click", function() {
        _link = $(this).attr("href");
        history.pushState(null, null, _link);
        loadContent(_link);
        return false;
    });

    function loadContent(href){
        $mainContent
                .find("#guts")
                .fadeOut(0, function() {
                    $mainContent.hide().load(href + " #guts", function() {
                        $mainContent.fadeIn(0, function() {
                            $pageWrap.animate({
                                height: baseHeight + $mainContent.height() + "px"
                            });
                        });
                        $("nav a").removeClass("current");
                        console.log(href);
                        $("nav a[href$="+href+"]").addClass("current");
                    });
                });
    }

    $(window).bind('popstate', function(){
       _link = location.pathname.replace(/^.*[\\\/]/, ''); //get filename only
       loadContent(_link);
    });

} // otherwise, history is not supported, so nothing fancy here.


});

It’s possible that there is a conflict with some of the WordPress code which is causing the problem. It is usually advisable to prefix any functions in added code such as this so that you are guaranteed that the function name is unique and doesn’t conflict with a WordPress function name. For example, in this code try renaming all instances of the function name loadContent() to gulliver_loadContent() or whatever prefix you would like to use.

Thanks.
That didn’t work.

Is the
console.log(href);
showing the href?

An even better alternative to that is to wrap the entire code in an IIFE so that it has its own separate namespace that can’t possibly conflict with any other variables.

1 Like

Thanks to you both.

The error was my failing to wrap the links in ‘nav’.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.