Working with HTML
A tagged template with HTML inside can be used to create a JS function that creates the DOM elements for the widget.
Consider the following example:
import html from "/lib/html"
const homepage= html`
<div name="root">
<h1>Current Viewport width</h1>
<div name="dynamicContent">
</div>
</div>
`
const {root, dynamicContent} = homepage()
document.addEventListener("resize", () => {
dynamicContent.innerHTML = `Current Viewport width: ${window.innerWidth}`
})
document.addEventListener("DOMContentLoaded", () => {
document.body.appendChild(root)
})
This is a fairly rudimentary solution and in no way a replacement for automatic reactive systems like React. But it does make the HTML more maintainable and easier to grok.
Also consider installing es6-string-html in VS Code to get syntax highlighting and prettier support for HTML strings inside the html strings.
Please note that the html tagged template returns a function. That function creates the DOM elements and returns the named ones. If you directly want the DOM elements:
const {root}= html`
<div name="root">
<h1>Current Viewport width</h1>
<div name="dynamicContent">
</div>
</div>
`()
Pay extra attention to the ()
at the end of the function call.
Typescript will catch the error for you, but pay attention nonetheless.