Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment

TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts

I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I'm facing challenges with getting the header navigation, which collapses into a hamburger icon on small screens, to function properly. Additionally, I'm unable to trigger my modals on button click, potentially because I haven't written additional JS for them. I suspect that dynamic elements like carousels may not work either.

I've successfully imported all necessary CSS, but importing the required JS for desired functionality has proven tricky.

In my components/header.js file, I've attempted the following code snippet. This setup allows me to easily reuse this code in any HTML files within the root folder:

headerTemplate.innerHTML = `
<style> 
    @import url("https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css");
    @import url("https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css");
</style>
<header>
    <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js”></script>
    <script type=”text/javascript” src=”https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js”></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

    // Rest of the header HTML code goes here...

`;

class Header extends HTMLElement {
    constructor() {
        super();
    }

    connectedCallback() {
        const shadowRoot = this.attachShadow({ mode: 'closed' });

        shadowRoot.appendChild(headerTemplate.content);
    }
}

customElements.define('header-component', Header);

Answer №1

Problem solved.

It turns out that following a tutorial and adding a shadow dom was the cause of my issue.

Here are the specific scripts I used in the HTML files with my components:

I didn't require popper or any extra dependencies.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8984849f989f998a9babdec5dac5d8">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8d80809b9c9b9d8e9fc2868c80819cafdec1dedfc1dc">[email protected]</a>/font/bootstrap-icons.css">
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js”></script> 
    <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js”></script>
    <script type=”text/javascript” src=”https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js”></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9f9292898e898f9c8dbdc8d3ced3cdd09c918d959ccc">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

Answer №2

I have a different idea to present:

index.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Page</title>
    <link rel="stylesheet" href="bootstrap.css" />
  </head>
  <body>
    <div id="navbarSection"></div>

    <script>
      fetch("navbarContent.html")
        .then((response) => response.text())
        .then((content) => {
          document.getElementById("navbarSection").innerHTML = content;
        });
    </script>
    <script src="bootstrap.bundle.js"></script>
  </body>
</html>

navbarContent.html :

<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</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 me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
          <a
            class="nav-link dropdown-toggle"
            href="#"
            role="button"
            data-bs-toggle="dropdown"
            aria-expanded="false"
          >
            Dropdown Menu
          </a>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><hr class="dropdown-divider" /></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled">Currently Unavailable</a>
        </li>
      </ul>
      <form class="d-flex" role="search">
        <input
          class="form-control me-2"
          type="search"
          placeholder="Search Here"
          aria-label="Search"
        />
        <button class="btn btn-outline-success" type="submit">Begin Search</button>
      </form>
    </div>
  </div>
</nav>

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

Retrieve the file name from the URL while disregarding the query string

Looking for a way to extract the test.jsp from this URL: http://www.xyz.com/a/test.jsp?a=b&c=d Can anyone provide guidance on how to accomplish this task? ...

What could be causing this Ajax error I'm experiencing?

I am attempting to dynamically load pages on this website using JQuery and Ajax when a menu point is clicked. However, I am encountering errors during the loading process. What does the console message ""GET 'path to css file'" mean? (there ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

The lack of flexibility in this element stems from the fact that it is not classified as a flex item

I'm facing an issue with flexbox and its unusual behavior. I have set up flexbox for the parent element and used flex: 1 1 100%, but it's not working as expected. When I checked in Firefox Developer Tools, it says that the parent is not a flex co ...

The "scrollTop" function seems to be malfunctioning in Firefox but works perfectly fine in Chrome. Is there a way to fix this issue?

Issue with scrollTop in Firefox jQuery(window).scroll(function(){ var NextScroll = jQuery(this).scrollTop(); if (NextScroll >= 800){ jQuery('#logomacchia').addClass("maccancello"); } else { jQuery('#logomacch ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

Selenium WebDriver is struggling to locate an element using link text

I'm currently facing a challenge in selecting an element that contains an anchor within a paragraph inside a div. The HTML structure I am working with is as follows: <a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATA ...

Maintain the flow of a floated or absolutely positioned element using CSS

Is there a way in CSS to ensure that floated or absolutely positioned elements remain within the flow? I find it frustrating that CSS lacks something like flow:on and flow:off to control this. The main issue I am facing is with having a div element of var ...

Navigating into iframe can be tricky when the previous iframe is not properly closed in Selenium Webdriver. Here

One issue we are facing is the excessive use of iframes in HTML. It has become troublesome to locate elements as some are buried within multiple layers of iframes. I'm trying to access an element inside the outermost iframe (the second one), but I&ap ...

An absolutely positioned element will always move within its relative container

After extensive searching on Google and Stack Overflow, I finally found what seemed like the perfect solution. The logic behind it made sense and I understood it perfectly. But when I implemented it, my absolute positioned divs kept moving whenever I resiz ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

The middleware function in my express server is not being identified

Currently, I am tackling server-side rendering in React and have developed a basic server in Express. However, I'm encountering the "TypeError('app.use() requires a middleware function')" error repeatedly. Below is a snippet of my app.js: v ...

Hovering over overlapping spans without moving them

For the text formatting, I attempted to use the following code: <style> #items { width:400px; padding: 10px; } .esp { float: left; background-color: yellow; position:relative; z-index:0; } .le { float: left; position:rela ...

Embed a React component within another component

Recently, I've started learning React and I'm utilizing material-ui for my project. My goal is to create a customized autocomplete feature in React where selected data from the dropdown will appear as chips inside the text input field. I am curre ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

Error: $this.text is throwing a TypeError and is not working as a function

Upon examining the code below: var $this = $(this).children('div.submenu1').children('a.subtile')[0], title = $this.text(), name = $this.attr('node').val; An error is encountered: Uncaught TypeError: $this.text is not a fun ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...