how to inject navigation using js & jquery

setup

you'll need the following:

  • a file named load.js (placed in the main directory)
  • a file for the page itself, to use as a template/base (can go anywhere)
  • a file for the text you want to inject (in this example, it's called "nav.html") (it is also placed in the main directory)

'load.js' is a jquery script that allows you to load in extra elements on a page from a different html file - this can be used as navigation, universal head tags, etc.... it can add a bit of load time, but it makes it easier to manage code that shows on every page.

the template itself will be very straightforward.

a visual guide to how this looks structurewise:

as you can see, we have three divs altogether - two classes (left and main, for navigation and content respectively), and a div id called "leftnav". what are we going to do with it? well, it uses javascript to grab text from nav.html. the specific 'call' for this looks like...

so that's the code you need to get that text in any particular place. but that's only if your load.js is configured right! so, moving on...

in your load.js file, you'll want this code:

this tells it to inject the contents of 'nav.html' into the div id 'leftnav'.

for the purpose of this tutorial, this will be the contents of 'nav.html':

and now, if you load your template file, the page looks like this:

you can see a live preview of this, slightly modified: click here

so to recap: you use that div id to insert any text you want. you can change the id name to whatever, and you can add more to the js file if you need more preloaded html to insert.

from here, it's just a matter of reusing the template you made (the div skeleton, as it were...) in every page going forward. this is how i do it, and it may not be perfect, but "It Just Work's" (tm)