1

I have header HTML page and I want to implement this header to all other HTML pages. Can I do it using HTML or JS? without PHP. I am a beginner in web programming and I made a simple frontend website using HTML and CSS.

header.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    
    <title>White Aim</title>
</head>
<body>
    <div id="header">
        <nav class="navbar navbar-expand-lg" >
            <div class="container-fluid">
                <a class="navbar-brand" href="index.html">
                    <img class="logo-style" src="assests/logo.svg" alt="White Aim">
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mb-2 mb-lg-0 navbar-text">
                    <li class="nav-item mx-2">
                        <a class="nav-link active" aria-current="page" href="index.html">الصفحة الرئيسية</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="about-us.html">نبذة عنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="our-experience.html">خبرتنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="contact-us.html">تواصل معنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="profile.html">الملف التعريفي</a>
                    </li>
                    </ul>
                </div>
            </div>
        </nav>
    </div>
</body>
</html>
Manal
  • 169
  • 1
  • 3
  • 15
  • 4
    Well, I would definitely recommend a server-sided solution such as PHP include. Alternatively, a JS Framework based on Node.js. The modern vanilla JS solution would be the usage of Web Components (not beginner stuff). PHP include (given that your webserver support PHP) a single line such as `` or `require`-methode. – tacoshy Jan 23 '23 at 08:24

2 Answers2

1

You could save the header code inside a global javascript variable and then render it with insertAdjacentHTML()

JS:

const header = `
    <div id="header">
        <nav class="navbar navbar-expand-lg" >
            <div class="container-fluid">
                <a class="navbar-brand" href="index.html">
                    <img class="logo-style" src="assests/logo.svg" alt="White Aim">
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mb-2 mb-lg-0 navbar-text">
                    <li class="nav-item mx-2">
                        <a class="nav-link active" aria-current="page" href="index.html">الصفحة الرئيسية</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="about-us.html">نبذة عنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="our-experience.html">خبرتنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="contact-us.html">تواصل معنا</a>
                    </li>
                    <li class="nav-item mx-2">
                        <a class="nav-link" href="profile.html">الملف التعريفي</a>
                    </li>
                    </ul>
                </div>
            </div>
        </nav>
    </div>
`;

document.addEventListener('DOMContentLoaded', (event) => {
  const homepage = document.querySelector('.homepage');
  homepage.insertAdjacentHTML('afterbegin', header);
});
<body class="homepage">
  <!-- CONTENT -->
  <script src="script.js"></script>
</body>

This way you could render your header variable in all the html files in which you include the script.js. Keep in mind that this is probably not a best practice, there are better ways to create HTML components, however this will do what you need using just vanilla JS without using external libraries or PHP.

proco
  • 11
  • 1
  • That's an interesting technique. Mind that this also causes an extra trip to the server to fetch the script. – metatron Jan 23 '23 at 09:15
0

The better way would be to use a php include. This lets the server do the include which saves a round trip.

<?php include 'footer.php';?>

It is also possible to import/include via Javascript on page load per what you asked (you asked for a non php solution). However it will cause another round trip to the server and unnecessarily slow your website down. I don't recommend it, but if you do want to go that route you can look at the Javascript script below based on https://www.w3schools.com/howto/howto_html_include.asp:

html:

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

js:

function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /* Loop through a collection of all HTML elements: */
  z = document.querySelectorAll("[w3-include-html]");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /* Make an HTTP request using the attribute value as the file name: */
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /* Remove the attribute, and call this function once more: */
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /* Exit the function: */
      return;
    }
  }
}

At the bottom of the page:

<script>
includeHTML();
</script>

You could also opt for a build step (preprocessing) at author time using a templating language. This makes things a bit more complex for a beginner, it is somewhat similar to writing php. But in contrast to php the html is assembled before the website is requested by users, al work is done before it is put online.

Some preprocessing languages are pug, ERB, haml, twig, ... here's a feature overview: https://css-tricks.com/comparing-html-preprocessor-features/

I don't use it but I know Adobe Dreamweaver has also a feature where you can include html snippets. It then builds the html with the included snippets which you can put online. But I don't recommend Dreamweaver.

metatron
  • 896
  • 7
  • 14
  • 1
    If I use PHP, so I have to change all pages extension from HTML to PHP? – Manal Jan 23 '23 at 08:43
  • That's the most common practice. Alternatively you could also tell your server to parse .html files as .php files. If you use .htaccess check here: https://stackoverflow.com/questions/4687208/using-htaccess-to-make-all-html-pages-to-run-as-php-files – metatron Jan 23 '23 at 09:05