PS - I am a non tech person but can create basic websites for small personal projects. I was working on a simple website where I needed to add a modal form using HTML/JS (Code below) and when I run it, it does not load the modal form on first click but works fine on the second click onwards. Tried researching but couldnt find anything or couldnt understand a lot of stuff. (The above code was derived from a form tutorial on W3schools)
< script >
function myfunc(fid) {
var modal = document.getElementById("myModal");
var btn = document.getElementById(fid);
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";
}
};
}
< /script>
<a id="myBtn" onclick="myfunc('myBtn')">Enquire Now</a>
CodePudding user response:
You should be able to just set the event listeners programmatically
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
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";
}
};
</script>
And then remove the onclick from the button element.
<a id="myBtn" >Enquire Now</a>
CodePudding user response:
You can accomplish the desired effect with a single delegated event handler that responds to click
events on some designated ancestor element... here it is the document
itself. The click
will trigger an event
that can be processed in the callback function to determine ( thanks to event bubbling/propagation ) which element triggered the callback and thus you can run whatever code you need within the suitably partitioned pieces of code.
document.addEventListener('click',e=>{
let dialog=document.querySelector('#myModal');
let span=dialog.querySelector('span.close');
if( e.target.id=='myBtn' ){
dialog.style.display='block'
}
if(e.target.className=='close' ){
dialog.style.display='none'
}
});
.close{
width:3rem;
height:3rem;
background:red;
display:inline-block;
text-align:center;
line-height:3rem;
}
.close:before{
content:'X';
color:white;
font-size:3rem;
cursor:pointer
}
#myModal{
display:none;
width:300px;
height:300px;
border-radius:1rem;
border:3px solid black;
margin:auto;
padding:1rem;
float:none;
}
.btn{
display:block;
width:120px;
text-align:center;
padding:1rem;
background:whitesmoke;
border:1px solid grey;
border-radius:0.5rem;
margin:1rem;
cursor:pointer;
}
<a id="myBtn" >Enquire Now</a>
<div id='myModal'>
<span class='close'></span>
</div>