Custom JavaScript UsageYou can write custom JavaScript to target the modal and attach behaviors. The following is an example of how you can use JavaScript to manipulate the Modal component. Please note that Bolt does not ship with any of this custom JavaScript.Demo
Automatically open a modalUse custom JavaScript to automatically open a modal on page load, after a short delay. Click on the "Activate JavaScript" button to see a demo. The page will reload and a modal will open after 3 seconds.
Auto-open Modal
This modal will open 3 seconds after page load.
Custom JavaScript<script>
// Add parameter to the URL - demo helper function, not required in production
var setAutoOpenModalParam = function(set){
var currentUrl = window.location.href.split('?').shift();
var param = '?showModal=true';
window.location.href = set ? currentUrl + param : currentUrl;
}
// Get parameter to the URL - demo helper function, not required in production
var getUrlParameter = function(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// Reference to the modal
var autoOpenModal = document.querySelector('#js-modal-advanced-auto-open');
// Calls modal 'show' method after a delay
var setAutoOpenModal = function(el) {
if (getUrlParameter('showModal')) {
setTimeout(function(){
el.show();
}, 3000)
}
}
// Callback on modal 'ready'
var onModalReady = function(e) {
setAutoOpenModal(autoOpenModal);
// IMPORTANT: remove this event listener unless you want it called each time the modal component renders
e.target.removeEventListener('modal:ready', onModalReady);
}
// Add 'ready' callback
autoOpenModal.addEventListener('modal:ready', onModalReady);
</script>Demo
Automatically close a modalUse custom JavaScript to automatically close a modal after a set period of time. Click on the "Open Modal" button to see a demo. The modal will open and automatically close after 3 seconds.
Auto-close Modal
This modal will close 3 seconds after opening.
Custom JavaScript<script>
openAutoCloseModal = function() {
// Reference to the modal
var autoCloseModal = document.querySelector('#js-modal-advanced-auto-close');
// When modal opens, start a timer and close after 3 seconds
var onModalShow = function() {
setTimeout(function() {
autoCloseModal.hide();
// Don't forget to remove the event listener
autoCloseModal.removeEventListener('modal:show', onModalShow);
}, 3000);
};
// Wait for 'modal:show' event and call custom function
autoCloseModal.addEventListener('modal:show', onModalShow);
if (autoCloseModal._wasInitiallyRendered) {
// If modal is ready, show it now
autoCloseModal.show();
} else {
// Otherwise, wait to show until 'modal:ready' event is emitted
autoCloseModal.addEventListener('modal:ready', function() {
autoCloseModal.show();
});
}
};
</script>