I’m attempting to trigger a bootstrap modal on a scroll event. I setup some JS to add the classes that I’ve seen show up when I trigger the modal with a button, thinking that by simply adding the classes then the modal would be toggled on, but it is not working. The scroll event listener is working, and it is adding the classes that would also be added by using the button. But there is a missing piece and I’m not sure what it is. I coded this JS to activate the classes:
const scrollModal = document.getElementById('scroll-modal'); // My Modal
const btn1 = document.getElementById('btn1'); // A button to test the click event
const showModal = function() {
let y = window.scrollY;
if (y >= 800) {
scrollModal.classList.add('show');
document.body.classList.add('modal-open');
} else {
scrollModal.className = 'modal';
document.body.classList = '';
}
}
window.addEventListener('scroll', showModal);
I used HTML directly from the BS docs:
<button id="btn1" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#scroll-modal">
Launch demo modal
</button>
<div id="scroll-modal" class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>