m0a
m0a

Reputation: 1005

How to make URL change upon clicking through AJAX loaded menu?

I've been following a video tutorial ( https://www.youtube.com/watch?v=ytKc0QsVRY4 ) on how to create a website that loads menus through AJAX. This is great, except I'd like the URLs to change so that the user has something to link to, and can also use the back and forward buttons on their browser properly.

How can this be achieved (hopefully so that it's compatible with what I've already been working on)?

Fiddle: http://jsfiddle.net/neowot/ru8potv4/

HTML:

<body>
    <ul id="nav">
        <li><a href="index">Home</a></li>
        <li><a href="about">About Us</a></li>
        <li><a href="contact">Contact</a></li>
    </ul>

    <div id="content">
        <h1>Content</h1>
    </div>
    <script></script>

</body>

CSS

body{
    background-color: aqua;
}

ul#nav {
    list-style:none;
    padding:0;
    margin: 0 0 10px 0;
}

ul#nav li {
    display:inline;
    margin-right:10px;
}

JS

$(document).ready(function() {
    //initial
    $('#content').load('content/index.php');

    //handle menu clicks
    $('ul#nav li a').click(function() {
        var page = $(this).attr('href');
        $('#content').load('content/' + page + '.php');
        return false;
    });

});

Upvotes: 0

Views: 606

Answers (1)

Chetan
Chetan

Reputation: 955

Set a hash(#) to the page url with user clicks on any link.. Check url hash on page load and on hashchange event.... then load respective page on that.

This way you can have unique url for each page and also browser back and forth buttons will work perfectly.

note: javascript hashchange event might not work in few older browser versions, so you might want to try any plugins available for that.

Upvotes: 1

Related Questions