Search code examples
javascripthtmlconstructorweb-componentinnerhtml

Web component not appearing in html file


I am trying to create a navigation bar using Web Components. I created a file called navbar.js where this is the code:

navTemplate = document.createElement('template');

navTemplate.innerHTML = `
    <style>
    nav {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color:  #0a0a23;
    }

    ul li {
    list-style: none;
    display: inline;
    }

    a {
    font-weight: 700;
    margin: 0 25px;
    color: #fff;
    text-decoration: none;
    }

    a:hover {
    padding-bottom: 5px;
    box-shadow: inset 0 -2px 0 0 #fff;
    }
    </style>
    <header>
    <nav>
    <ul>
        <li><a href="work.html">Work</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
    </nav>
    </header>
    `;

class Navbar extends HTMLElement {
constructor() {
    super();
    this.root = this.attachShadow({ mode: 'open' });
    this.root.appendChild(navTemplate.content);
}} customElements.define('my-navbar', Navbar);

I call this code using my-navbar in the body and script src="components/navbar.js" in the head because my .js file is in a components folder. However my navigation bar is not showing up. Is the issue in the innerHTML? The constructor? Why is it not showing up?


Solution

  • Good news is that the component itself is working - when we inlined the code in an HTML file, we could use the my-navbar tag as expected. So the issue may be the way you load your file. Furthermore, using a components\navbar.js file as suggested and loading it into an html file (in head, at beginning of body, or at the end of the body), we were also able to load and use the component.

    So check your html file and verify in DevTools that the JS is loaded correctly.