Question

I have a navigation that loads content into a specific element on the page via AJAX:

<ul class="main-nav-child">
    <li><a href="/collections/page1">page 1</a></li>
    <li><a href="/collections/page2">page 2</a></li>
    <li><a href="/collections/page3">page 3</a></li>
</ul>

The following snippet makes that happen:

$('ul.main-nav-child a').bind('click', function(e) {           
    var url = $(this).attr('href');
    $(".main-content").load(url + " .product-grid-collection");
    e.preventDefault(); // stop the browser from following the link
});

My question is this: How can I update the URL in the browser to reflect the link that's been clicked and also addClass of .active to that link (and removeClass from the previous active link), without refreshing the page?

UPDATE: So I've now managed to get the URL to change when a link's clicked, I just need to addClass of .active to each link when clicked and removeClass .active for the previous link.

Here's my updated code:

$('ul.main-nav-child a').bind('click', function(e) {           
    var url = $(this).attr('href');
        $(".main-content").load(url + " .product-grid-collection");
        e.preventDefault(); // stop the browser from following the link
        var stateObj = { foo: "bar" };
        history.pushState(stateObj, "", url);
});

Any help/advice is greatly appreciated.

Était-ce utile?

La solution

i think you are looking for "replace with" in conjunction with hijacking links jQuery: hijack a link and find its parent

this will take a link replace your current html page with out reloading and then you can add the link to your custom pushstate array giving you the appearance of a one page application

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top