-1
I have several buttons on a page of a wordpress site, I set all these buttons with the click class, when the user click one of the buttons I have to grab the id of the button clicked, with this id I grab the element and trigger a function that opens a modal. However when I test in the browser it works normally in wordpress it gives the following error: Cannot read Property 'addeventlistener' of null, why?
Script
$(document).ready(function(){
function iniciaModal(modalID){
const modal = document.getElementById(modalID);
if(modal){
modal.classList.add('mostrar');
modal.addEventListener('click', (e) =>{
if(e.target.id == modalID || e.target.className == 'fechar'){
modal.classList.remove('mostrar');
}
});
}
}
$('.click').click(function(){
var id = $(this).attr('id');
const idButton = document.getElementById(id);
idButton.addEventListener('click', () => iniciaModal('modal-form-popup'));
});
})
HTML Modal:
<div id="modal-form-popup" class="modal-containerPopup">
<div class="modalPopup">
<button class="fechar">x</button>
<h3>Teste</h3>
<form>
<input type="text">
<input type="submit">
</form>
</div>
CSS:
.modal-containerPopup{
width:100vw;
height: 100vh;
background:rgba(0,0,0,.1);
position: fixed;
top: 0px;
left: 0px;
z-index:1000;
display: none;
justify-content:center;
align-items:center;
}
.modal-containerPopup.mostrar{
display: flex;
}
.modalPopup{
background:white;
width:60%;
padding: 25px;
border: 6px solid black;
position:relative;
}
@keyframes modal {
from{
opacity: 0;
transform: translate3d(0, -60px, 0);
}
to{
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
.mostrar .modalPopup{
animation: modal .3s;
}
.fechar{
position:absolute;
font-size: 1em;
top:-30px;
right:-30px;
width:30px;
height:30px;
border-radius: 50%;
border: 4px solid white;
background: #35baf2;
color: white;
box-shadow: 0 4px 4px 0 rgba(0, 0, 0, .3);
cursor: pointer;
display:flex;
align-items:center;
justify-content:center;
}
The getElementById method returns null when no element is found. This means that its class element "click" has no attribute of type id: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
– Ricardo Passos
@Ricardopassos was worth Ricardo, that’s right I’m very inexperienced with wordpress
– Roger
@Ricardopassos can give me an agr tip everything is working but, I need to give two clicks on the button pq I fired when click on the class, dps when he picks up the element with that id to fire the modal as I would do everything with a single click?
– Roger