Satch3000 Satch3000 - 5 months ago 11
Javascript Question

Javascript csi and navigation (no iframes)

I am importing external html files using jQuery like this:

$("#header").load("header.html");

$("#content").load("home.html");

$("#footer").load("footer.html");


And the html:

<html>
...
<body>

<div id="header"></div>

<div id="content"></div>

<div id="footer"></div>


</body>
</html>


What I want to be able to do is to also have this:

Import the Nav:

$("#hav").load("nav.html");

Into:

<div id="nav"></div>


So I would have:

<html>
...
<body>

<div id="header"></div>
<div id="nav"></div>

<div id="content"></div>

<div id="footer"></div>


</body>
</html>


The nav import would look like this:

<ul>
<li><a href="home.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>


Now, this is the hard part...

I need the pages from the nav to open in the content area but I need the header and footer to stay loaded as they are and only the content area to change.

How can I do this without iframes or angular (as I know angular can do this).

Answer

I haven't tested this out, but here's a way that might work.

$('#nav').on('click', 'li a', function(evt) {
  evt.preventDefault();
  var href = $(this).attr('href');
  $('#content').load(href);
});

The listener is added to #nav only because that element exists at the time the listener is made, but it's actually listening for any bubbled elements of children, fitting the selector.

The preventDefault() is meant to prevent regular navigation from taking place. If that doesn't work, you could try the same with a link in appearances-only. (eg, <span class="linkLike" data-href="about.html">About</span>)