Jamie Lindsey
Jamie Lindsey

Reputation: 993

Issues with history.pushState

I am trying to implement history.pushState while using .load() function to load content without redirecting the page, the .load() functionality works fine, and the history.pushState works on the first implementation. But when I then click another link it appends to the url...

Here's what I mean:

Main URL: https://materialwebdesign.ltd
Click link and URL becomes: https://materialwebdesign.ltd/inc/material-design
Click another link and URL becomes: https://materialwebdesign.ltd/inc/inc/bootstrap

Why is this happening? Heres my code:

$(document).ready(function() {

    $('#main_content').load('inc/main-content.html', function() {
        $(this).animate({ height: '100%', width: '100%' }, 2000, 'linear');
    });

    $('.dynamic').click(function(e) {

        e.preventDefault();

        var page = $(this).attr('href');

        var title = page.title;

        $('#main_content').html('<div class="mdl-spinner mdl-js-spinner is-upgraded is-active"></div>');

        if (typeof (history.pushState) != 'undefined') {

            var obj = {Title: title, Url: page}

            $('#main_content').load(page + '.html', function() {
                $(this).animate({ height: '100%', width: '100%' }, 2000, 'linear')
            });

            if(page != window.location){
              history.pushState(obj, obj.Title, obj.Url);
            }

            return false; // don't follow the link

        };

    });
});

As well as the problem mentioned above, the animation just doesn't animate, if you could help with that too I would appreciate it very much

Upvotes: 1

Views: 1067

Answers (1)

Barmar
Barmar

Reputation: 782693

obj.Url is a relative URL, so it's interpreted relative to the current URL of the page. Since it contains a subdirectory, every time you do this you add another level of subdirectory to the current page's URL.

Instead of $(this).attr('href'), which returns the relative URL in the attribute, use this.href -- this will return the href property, which is an absolte URL after canonicalization.

Upvotes: 1

Related Questions