Saskia Saskia - 2 months ago 17
Javascript Question

JavaScript onClick: I have to click twice for modal to appear

I am trying to add a click event to a button element with a dynamically changing id. However to actually get the popup to appear, I have to click the button twice... I know it is happening like this, because I am doing something wrong with click event. But I can't figure out how to solve the issue.
Can you? I am pulling my hair out over this...

Thanks so much in advance



// Get the modal
function getPopup(venue_id){
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn"+venue_id);
var venue = document.getElementById("title"+venue_id).innerHTML;
document.getElementById("eventTitle").innerHTML = "<h3>"+venue+"</h3>";
var span = document.getElementsByClassName("close")[0];



btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}


function sentPopup(){
document.getElementById('myModal').style.display ="none";
var modal = document.getElementById('thanksMessage');
var span = document.getElementById("close");
modal.style.display = "block";
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}

<?php /* $venue_id is being populated by a php function which doesnt matter for this click issue to solve */
<button class="btn" id="myBtn'.$venue_id.'" onclick="getPopup('.$venue_id.')">Unverbindlich anfragen</button>

<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">x</span>
<p class="venuePopupTitle" id="eventTitle"></p>
<form>my form</form>
</div>
</div>
?>




Answer

Saskia, the reason you need to click twice, is that this:

btn.onclick = function() {
    modal.style.display = "block";
}

Is inside the getPopUp function, which only gets called when you click the button. So when you click once, only then, it sets the onclick function to button.

You need to change this lines to perform the action immediately, so inside getPopUp, you need to do:

modal.style.display = "block";

Without the btn.onclick.

The same for the other button inside sentPopUp because you will have the same issues.

I would recommend you get rid of inline onclick attributes in your HTML and use unobtrusive style of writing javascript to avoid errors.