Once you've created a header and footer you may be wondering how run javascript on its contents.
Headers and Footers are isolated from the rest of the page in order to prevent styling conflicts. This is done using the Shadow DOM. This means a normal method of querying/modifying a DOM node won't work.
Don't worry though, all that's need is a minor modification.
Example without Shadow DOM
Let's say we wanted to add a click event handler to a button in our header. Without a shadow DOM we would do it like this.
header.html
<header>
<button type="button" id="headerButton">Click Me!</button>
</header>
javascript.js
onVanillaReady(function() {
// Find the button.
var button = document.querySelector("#headerButton");
if (button) {
// Best to always check the your item was found. Otherwise you might crash the page.
button.addEventListener("click", function (e) {
alert("Button was clicked!");
});
}
});
Why doesn't this work?
document.querySelector
will not find any element because your button has been rendered inside of a shadow DOM. Let's see an example of how to make this work.
Working Example with Shadow DOM
header.html
Same as above.
javascript.js
onVanillaReady(function () {
// Get access to the root of the header.
// THIS IS THE CHANGE
var themeHeader = document.querySelector("#themeHeader").shadowRoot;
// Find the button.
var button = themeHeader.querySelector("#headerButton");
if (button) {
// Best to always check the your item was found. Otherwise you might crash the page.
button.addEventListener("click", function (e) {
alert("Button was clicked!");
});
}
});
All that was needed as a change was querying the shadow root of the header.