Multiple pages same CSS/JS file but different URL

Viewed 310

I'm making a website with different pages; let's say:

  • Home
  • About me
  • Contact

All those pages have the same structure

<div id="PageWrapper">
   <header id="PageHeader">
      <nav id="MainMenu">
         <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>
      </nav>
   </header>

   <div id="PageContent"></div>
</div>

where in PageContent will be filled by the page content.

Since all those pages have the same structure, I would like to have an Index.html page with the structure and then load all the contents from different html files instead of creating n pages with same structure and copying and past the link to CSS and JS files.

I've tried using function from JQuery in the following way

$('#MainMenu ul li a').click(function(e) { 
   appendPage($(this).attr('href'));
   e.preventDefault();
});
    
function appendPage(url){
   window.location.hash = url;
   $.ajax({
      url: url
   }).done(function(data) {
      $('#PageContent').html(data);
    });
}

this works but the problem is it doesn't really change the URL of the page. If I save the url and I would like to go directly to Contact page, it will reload the page from the Home

1 Answers

Just make a folder called pages and ensure all your links follow the same name as your file names.

So you'd have a pages directory with home.html, about.html, etc.

<div id="PageWrapper">
   <header id="PageHeader">
      <nav id="MainMenu">
         <ul>
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
         </ul>
      </nav>
   </header>

   <div id="PageContent"></div>
</div>
$('#MainMenu ul li a').click(function(e) {
   e.preventDefault();
   insertContent($(this).attr('href'));
});

function insertContent(pageHref){
   pageHref = pageHref.replace('#', '');
   $.ajax({
      url: `pages/${pageHref}.html`,
   }).done(function(data) {
      $('#PageContent').html(data);
   });
}

// Initialize content based on window location hash
window.onload = insertContent(location.hash);
Related