Home > Software design >  loading html via js, the css in the html does not work. bootstrap 5
loading html via js, the css in the html does not work. bootstrap 5

Time:02-22

Im using bootstrap 5. In index.html, im inserting the nav.html via js. The problem is, the navbar CSS doesnt work when loaded via js. But does work if i copy the nav.html code itself into index.html.

ie. the main.css colors for navbar and navbar-brand are not showing when nav.html is loaded into index, but the colors do show when the nav code is in index, and not using the js loading.

The nav.html gets copied into many pages, thats what i want, but there is no styling. why?

index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="stylesheet" href="main.css">
  </head>
  <body>

    <div >
      <div >

            <!--Navigation bar-->
            <div id="nav-placeholder"></div>
            <script>
              $(function(){ $("#nav-placeholder").load("nav.html") });
            </script>
            <!--end of Navigation bar-->

      </div>
    </div>
  </body>
</html>

nav.html

<nav >
  <a  href="index.html">My Co.</a>
  <button  type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span ></span>
  </button>

  <div  id="navbarSupportedContent">
    <ul >
      <li >
        <a  href="legal.html">Legal</a>
      </li>
      <li >
        <a  href="faq.html">FAQ</a>
      </li>
      <li >
        <a  href="about.html">About</a>
      </li>
    </ul>
  </div>
</nav>

main.css

.navbar {
  background-color: #ff00ff;
}
.navbar-brand {
  color: #ff0000;
}

CodePudding user response:

In the Network tab of the developer console, what is the status code ? It could just be a wrong path of your html file.

Without self-invoking expression it should work:

$("#nav-placeholder").load("nav.html");

Or if you still want a self-invoking expression:

(function(){ $("#nav-placeholder").load("nav.html"); })();

CodePudding user response:

stupid me. its the order of my css.

ie.

from

to

the nav css displays correctly with the colors in main.css

  • Related