Skip to content

Importing HTML

Now we want to create some HTML structure in our container. Instead of creating each element by code we will outsource the HTML structure in an own file.

For this we will get help from two further libraries: Bottstrap and Font Awesome. To install these libraries and inject them automatically we will use the @cc-external directory like in the chapter before:

1
2
npm i @cc-external/bootstrap
npm i @cc-external/fortawesome_fontawesome-free

Now we create a new file with the HTML structure that we want to use:

src/amazing-button.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<div class="amazing-button card h-100">
  <div class="card-header">
    Amazing Button <i class="fa fa-magic"></i>
  </div>
  <div class="card-body">
    <h5 class="card-title">Click on the button to see the miracle</h5>
    <p class="card-text">
      <button class="btn btn-secondary">Bootstrap Press Me</button>
    </p>
    <div class="result border border-primary">No Result</div>
  </div>
</div>

We write now a new class that imports this structure and insert it into the container element (both relevant places highlighted in yellow):

src/amazing-button-bootstrap.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import $ from "jquery";
import htmlTemplate from "./amazing-button.html";
export default class {
  #maximumNumber;
  get maximumNumber() {
    return this.#maximumNumber;
  }
  set maximumNumber(value) {
    this.#maximumNumber = value;
  }
  constructor(element) {
    $(element).html(htmlTemplate);
    $(element).css({
      border: "1px solid red",
      textAlign: "center"
    });
    $(element)
      .find("button")
      .on("click", () => {
        this.resultDiv.html(
          Math.floor(Math.random() * (this.#maximumNumber ?? 9))
        );
      });
    this.resultDiv = $(element).find("div.result");
  }
}

Finally we will change the index.js and switch to our new Bootstrap based library:

src/index.js

1
2
3
import { default as AmazingButton } from "./amazing-button-bootstrap";
let myClass = new AmazingButton(document.getElementById("test-container"));
myClass.maximumNumber = 99;

Now you should see the running example in your browser.