Bootstrap JavaScript Snippets
Contents
When working on building websites with Bootstrap I often find myself copying and re-using a bunch of useful little JavaScript snippets to enhance functionality and I thought I’d make a quick blog post to share a few of my most used ones. They are all for Bootstrap 5, but could easily be adapted for earlier versions.
Open Modal via URL Fragment
It can sometimes be useful to have a shareable URL which, automatically opens a modal on page load. e.g. Test. This can be achieved with this little script.
document.addEventListener("DOMContentLoaded", function() {
if (window.location.hash === "#exampleModal") {
const modalElement = document.getElementById("exampleModal");
if (modalElement) {
const modal = new bootstrap.Modal(modalElement);
modal.show();
}
}
});
Open Accordion via URL Fragment
It can sometimes be useful to have a shareable URL which, automatically opens an accordion section on page load, perhaps to show a specific section of content.
document.addEventListener("DOMContentLoaded", function () {
const hash = window.location.hash;
if (hash) {
const buttonElement = document.querySelector(hash + " .accordion-button");
if (buttonElement) {
buttonElement.click();
}
}
});
Prevent Modal from Playing Video When Closed
If you have a modal with a video in it, you may want to prevent the video from continuing to play when the modal is closed. This can be done by resetting the src attribute of the <iframe> when the modal is hidden.
You can test this by clicking the button below which will open a modal with a YouTube video in it. When you close the modal, the video will stop playing.
document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("hidden.bs.modal", function (event) {
const iframes = event.target.querySelectorAll("iframe");
iframes.forEach(function (iframe) {
const currentSrc = iframe.src;
iframe.src = "";
setTimeout(function() {
iframe.src = currentSrc;
}, 100);
});
});
});
Dismiss Tooltips on Escape
I hope this feature is added to Bootstrap itself (I opened an issue!) as it’s needed for full WCAG21 compliance. You can test this by hovering over the share link button below this article which will display a tooltip and then pressing the Esc key.
document.addEventListener("keyup", function (event) {
if (event.key === "Escape") {
const tooltipTriggerList = document.querySelectorAll(
'[data-bs-toggle="tooltip"]',
);
tooltipTriggerList.forEach(function (tooltipTriggerEl) {
var tooltip = bootstrap.Tooltip.getInstance(tooltipTriggerEl);
if (tooltip) {
tooltip.hide();
}
});
}
});