Trying to manage multiple modals on an HTML page using a JavaScript object literal. Unfortunately, encountering an error when attempting to display the modal by clicking a button.
Uncaught TypeError: this.showModal is not a function
at HTMLButtonElement.modalBtns.(anonymous function).onclick (file:///C:/dj-sites/ux_bee/js/base.js:63:22)
Suspecting that the issue lies in the "this" keyword, which seems to be referencing the button instead of the object literal. Need to figure out how to resolve this.
var myModalObj = {
findAncestor: function(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
},
showModal: function(btn){
var modal_id = btn.getAttribute('data-modal')
var modal = document.getElementById(modal_id);
modal.style.display = "block";
},
closeModal: function (btn){
var modal = this.findAncestor(btn, 'modal')
modal.style.display = "none";
},
init: function(){
var modalBtns = document.getElementsByClassName('my-modal-btn');
for(var i = 0; i < modalBtns.length; i++) {
var btn_modal = modalBtns[i];
modalBtns[i].onclick = function() {
this.showModal(btn_modal);
}
}
var closeBtns = document.getElementsByClassName('modal-close');
for(var i = 0; i < closeBtns.length; i++) {
var btn_close = closeBtns[i];
closeBtns[i].onclick = function() {
this.closeModal(btn_close);
}
}
}
}
myModalObj.init()