Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 5 : show modal with javascript

I'm making a neat gallery with bootstrap 5, and I wondered how I could trigger a bootstrap modal without using "data-bs-..." in my HTML (to avoid duplicating those data- attributes 50 times).

I managed to get a full functionning javascript for the sources, but the .modal() functions and .show() functions don't seem to work. Here's the thing :

function gallery(_src) {
var fullPath = _src;
var fileName = fullPath.replace(/^.*[\\\/]/, '');
var newSrc = "./assets/img/" + fileName;
document.querySelector("div#galleryModal img").src = "./assets/img/" + fileName;

document.getElementById("galleryModal").show(); }

I'm blocked on this last javascript line. The objective : trigger #galleryModal.

Thanks for reading, thanks for helping !

like image 462
Horkos Avatar asked May 12 '26 19:05

Horkos


1 Answers

We need to Create a modal instance if we want to operate with javascript check the below code and you find more info https://getbootstrap.com/docs/5.0/components/modal/#via-javascript

var galleryModal = new bootstrap.Modal(document.getElementById('galleryModal'), {
  keyboard: false
});


galleryModal.show();
like image 57
nmanikiran Avatar answered May 14 '26 10:05

nmanikiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!