IAmYourFaja
IAmYourFaja

Reputation: 56912

URL-based single page app nav in pure JavaScript?

I'm trying to write a single-page web app in JavaScript. Desired behavior:

I'm wondering how to do this. I'd greatly prefer something jQuery-based rather than trying to write something homegrown. But if I have to write this code myself, then given the following general structure of the 1 HTML file:

<html>
    <head> ... </head>
    <body>
        <div id="home" class="page">
            <!-- Content for home page, say http://myapp.example.com/#home. -->
        </div>

        <div id="about" class="page">
            <!-- Content for About page, say http://myapp.example.com/#about. -->
        </div>

        <div id="contact" class="page">
            <!-- Content for Contact page, say http://myapp.example.com/#contact. -->
        </div>

        <!-- Etc. for all other "pages" -->         
    </body>
</html>

How do I:

Upvotes: 2

Views: 2449

Answers (4)

Jamie Barker
Jamie Barker

Reputation: 8246

If you want to abuse the browser history, I suggest you read this article on history.pushState(). :-)

Upvotes: 0

joninx
joninx

Reputation: 1780

That is the reason of Single Page Application Framework's existence. I think it does worth learning some of the, such as AngularJS or BackboneJS.

Upvotes: 0

joninx
joninx

Reputation: 1780

I think you should hide every div at start.

$(div#page).hide();

Then, you can check the current URl by using:

var pathname = window.location.pathname;

Every time the user changes the URL: first hide every div, then check and show the desired div.

Upvotes: 2

nl-x
nl-x

Reputation: 11832

You can use and set the window.location.hash and use that value to $("#yourDivId").show() and $("#yourDivId").hide() your divs.

On the onload you can $("#yourDivId").show() the requested (or default if none was requested) div, and $("#yourDivId").hide() the other divs.

And on each link, either directly change the hash and set the requested div visible. Or set a timer that checks the hash on an interval to see if the hash has changed. (There is no native onhashchange event.)

Upvotes: 2

Related Questions