Skip to content

Instantly share code, notes, and snippets.

@lenamtl
Forked from signalpoint/README.md
Created April 2, 2021 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenamtl/533e7f20432efdd210a3b6e393ec55eb to your computer and use it in GitHub Desktop.
Save lenamtl/533e7f20432efdd210a3b6e393ec55eb to your computer and use it in GitHub Desktop.
Bootstrap 4 Dynamic Modal with JavaScript

Use this to dynamically create and set the content of a Bootstrap 4 Modal.

In this example, we chose an onclick handler to initialize the modal (only once), and then set the content of the modal dynamically.

<button type="button" class="btn btn-outline-primary" onclick="exampleOnclick(this)">Taco Tommy</button><br />
<button type="button" class="btn btn-outline-primary" onclick="exampleOnclick(this)">Bobby Burrito</button>
function exampleOnclick(btn) {
var name = btn.innerHTML;
var exampleModal = getExampleModal();
// Init the modal if it hasn't been already.
if (!exampleModal) { exampleModal = initExampleModal(); }
var html =
'<div class="modal-header">' +
'<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>' +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
'</button>' +
'</div>' +
'<div class="modal-body">' +
name +
'</div>' +
'<div class="modal-footer">' +
'<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
'<button type="button" class="btn btn-primary">Save changes</button>' +
'</div>';
setExampleModalContent(html);
// Show the modal.
jQuery(exampleModal).modal('show');
}
function getExampleModal() {
return document.getElementById('exampleModal');
}
function setExampleModalContent(html) {
getExampleModal().querySelector('.modal-content').innerHTML = html;
}
function initExampleModal() {
var modal = document.createElement('div');
modal.classList.add('modal', 'fade');
modal.setAttribute('id', 'exampleModal');
modal.setAttribute('tabindex', '-1');
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-labelledby', 'exampleModalLabel');
modal.setAttribute('aria-hidden', 'true');
modal.innerHTML =
'<div class="modal-dialog" role="document">' +
'<div class="modal-content"></div>' +
'</div>';
document.body.appendChild(modal);
return modal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment