Tutorial on embedding navigation menu from an external file without using Wamp; all the code should be executed on the client-side

I am trying to find a way to store my top navigation menu in an external file for my static HTML website. I want to be able to easily update the menu and see those changes reflected on all pages without needing to upload them to a server. It's important that I can view the web pages locally as well, without relying on additional software installations.

I have come across solutions using PHP, SSI, and frames to address this issue, but none of them seem to fit my specific requirements. Frames are outdated and not ideal for SEO purposes, while PHP and SSI only work once the site is uploaded to a server.

  • Frames are out of the discussion due to their impact on SEO and obsolescence with HTML5.
  • PHP and SSI won't function locally and can only be used after uploading the site to a server.

After exploring various options, I believe storing the entire menu in an external JS file could be a viable solution. However, most existing examples still include some parts of the menu within the HTML file. Is it possible to have all menu items stored in a JS file and simply call that file in my HTML without including the actual menu items directly in the HTML?

I have basic knowledge of JavaScript and believe I can make necessary adjustments to a generic example to suit my needs.

Answer №1

navigation.html

<ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="active1.html">Contact</a></li>
    <li><a href="active2.html">About</a></li>
    <li><a href="active3.html">Portfolio</a></li>
</ul>

index.html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

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

Javascript file:

$(function() {

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

    function activateNavigation() {
        var pageUrl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
         $("#nav ul li a").each(function(){
              if($(this).attr("href") == pageUrl || $(this).attr("href") == '' )
              $(this).addClass("active");
         });
    }

    setTimeout(function() {
        activateNavigation();
    }, 100);

});

The setTimeout allows the page to load and then executes the function to determine which link is active, allowing you to apply a CSS class:

#nav ul li a.active {
        color: #ff0000;
        font-weight: bold;
    }

Answer №2

nav.html // simply include the nav section without any extra tags.

<nav> bla bla </nav>

index.html

<!doctype html>
<html>

  <head>
    <title>onload test</title>
    <script>

    window.onload = function(){
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
             document.getElementById('includeNav').innerHTML= '<object type="text/html" data="nav.html"></object>';
        }
    }

    xhttp.open('POST', 'nav.html', true); // method, location, async
    xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhttp.send(); }
    </script>
  </head>


  <body>
    <p>The load event fires when the document has finished loading!</p>
    <div id="includeNav"></div>
  </body>
</html>

Give it a shot. It could be the solution you're looking for.

Answer №3

If you're interested, delving into HTML Imports could be worthwhile.

Method 1: A basic implementation could look something like this:

index.html (or any other page):

<!DOCTYPE html>
<html>
<head>
    <link rel="import" href="nav.html">
</head>
<body>
    My Page
    <script>
        var link = document.querySelector('link[rel="import"]');
        var nav = link.import.querySelector('nav');
        document.body.appendChild(nav.cloneNode(true));
    </script>
</body>
</html>

nav.html:

<nav>
    <ul>
        <li>link 1</li>
        <li>link 2</li>
        <li>link 3</li>
    </ul>
</nav>

More insights at: http://www.html5rocks.com/en/tutorials/webcomponents/imports/

Method 2: Utilize the Web Components API fully and create your own HTML element, making usage across files more streamlined (despite a slightly more complex nav.html).

index.html (or any other page):

<!DOCTYPE html>
<html>
<head>
    <link rel="import" href="nav.html">
</head>
<body>
    My Page
    <my-nav></my-nav>
</body>
</html>

nav.html

<nav>
    <ul>
        <li>link 1</li>
        <li>link 2</li>
        <li>link 3</li>
    </ul>
</nav>
<script>
    var navProto = Object.create(HTMLElement.prototype);
    var navDoc = document.currentScript.ownerDocument;
    navProto.createdCallback = function() {
        var shadow = this.createShadowRoot();
        var nav = navDoc.querySelector('nav');
        var clone = document.importNode(nav, true);
        shadow.appendChild(clone);
    };
    document.registerElement('my-nav', { prototype: navProto });
</script>

REMARK: One caveat to consider in both options is browser compatibility:

Mainly supported by Chrome (including Android) and Opera. Regrettably, using HTML imports without a web server isn't feasible due to browser security settings. You might encounter a console error similar to this:

Imported resource from origin 'file://' has been blocked 
from loading by Cross-Origin Resource Sharing policy: 
Invalid response. Origin 'null' is therefore not allowed access.

Thus, starting a simple web server such as the nodejs module http-server or employing a Chrome extension like Chrome Dev Editor with a built-in web server becomes necessary https://chrome.google.com/webstore/detail/chrome-dev-editor/pnoffddplpippgcfjdhbmhkofpnaalpg?utm_source=chrome-app-launcher-info-dialog

Answer №4

Here is a solution I shared in a previous post:

To achieve this without the need for a server side language, you can utilize a javascript library such as W3Data. Simply add the w3-include-html attribute to your div element and you're all set!

For instance, if your menu content is stored in a file named menu.html, you can implement it like so:

<div w3-include-html="menu.html"></div>

Answer №5

A great tool to consider for this task is JsRender/JsViews.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making a Highcharts Pie Chart Legend Embedded Within a Table

Looking for a way to incorporate a Highcharts legend into a table layout? I am aiming to design the legend for my Highcharts pie chart with alternating background colors and custom borders for each element. Although I have styled the legend, I am struggli ...

Tips for sending a query from JavaScript code to a server using AJAX

I have an upcoming event where, upon clicking the right button on a marker, google.maps.event.addListener(marker, 'rightclick', (function (marker) { a function is returned: return function () { marker.setMap(null); delete markerBusyBrID[this.mark ...

Basic demonstration of AngularJS including a module and controller showcased on jsFiddle

I have a question regarding jsFiddle and Angular. I am currently learning the basics of Angular and I noticed that my code only works when I include the controller JS in the HTML pane. You can view my jsFiddle here. Here is the code that works: <div n ...

Stacking images with CSS styling

I'm currently working on creating a CSS design template. Within this project, I have two images named imageOne and imageTwo. Both images are styled with position: relative, as setting one to position: absolute would compromise the responsiveness of ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box. <!-- HTML code for changing zip c ...

Transferring information submitted in a form to a service using AngularJS

Trying to implement a shopping cart app where I need to pass an object into a service function using Angular. Following advice from another post, but encountering an unprovided error and a strange syntax error on page load. The issues seem to be originatin ...

What is the best way to verify the success or error callbacks of an AJAX request?

We have the option to include AJAX callback functions in various sections: $.ajax(url,{ data:data, ..., success:successCallback1, error:errorCallback1 }) .success(successCallback2) .error(errorCallback2) .done(successCallback3) .fail(errorCallb ...

Observing data retrieved via ajax in Internet Explorer 9

Is there a way to view data returned by an ajax script in Internet Explorer 9? For instance, Firefox has the Firebug 'All' tab with a 'Response' Sub Tab that displays data returned by an Ajax Script. How can this be done in Internet Ex ...

What is the reason behind my page automatically scrolling to the bottom when it loads?

I am currently working on a project for my company, and unfortunately, I cannot share the code as it is proprietary. However, I am encountering a problem where the page loads and automatically scrolls to the bottom. I have checked for any unclosed tags in ...

What is the technical process behind conducting A/B testing at Optimizely?

I'm currently experimenting with Google Analytics and Content Experiments for A/B testing on my website, but I'm encountering some challenges in making it seamless. To utilize the Google API properly, a few steps need to be taken. Firstly, I nee ...

Using Protractor to extract text from multiple paragraphs

How do I retrieve the values of all paragraphs (p) at once? Below is an example of how my inspect view appears: "Testing sample one." "Testing sample two." And here is a snippet of my code to extract the value of id 'run': browser.findElement ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

Utilizing Ajax to Populate a Dropdown List with Data

Currently, I am retrieving data from an API. The data consists of IDs and charity names that need to be displayed in a dropdown list. While I have successfully shown the charity names in the dropdown list, I am struggling with including the IDs. How can I ...

Eliminating empty space within my container

I am facing an issue with a container that contains an image and a button on top of it. There seems to be some extra space created within the container on the right side which is taking up more space than necessary. The layout consists of three horizontal ...

The hover effect for a :before class is not functioning as intended

I have created a dropdown menu with a triangle at the top in this style: When the cursor hovers over only the triangle, it appears like this: However, when the cursor is over the div, the hover effect for both elements is activated as shown here: I am t ...

Learning the integration of vuex with defineCustomElement in Vue 3.2

V3.2 of Vue introduces the ability to create custom elements with the defineCustomElement feature. Learn more here. Can anyone explain how to connect a store (Vuex) with a defineCustomElement? ...

Toggling markers according to form selections is not functioning

My goal is to dynamically show or hide markers on my Google Map that represent houses and condos, based on the features selected by the user from a select box with id #features. For example, if a user picks 'Swimming Pool' as a feature and click ...

WordPress: Struggling to Show Sub-Menu on Hover Feature Not Functioning

I'm having trouble getting the .sub-menu to appear when hovering over the 'about' page in my WordPress navigation. It doesn't seem to be working as expected. I'm not sure whether the issue lies with my jQuery or my CSS. What modif ...

Retrieving information from controller to HTML page in AngularJS

Check out my code on Plunkr: http://plnkr.co/edit/8sBafktFzFa8fCLLJgMF This is the JavaScript file: angular.module('ui.bootstrap.demo', ['ui.bootstrap']); angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl&ap ...