I have Modal box popin with some text wrapped in a function. This modal is displayed when you click on a div.
Now I want to add a separate script with a div and when you click this div I want it to call the modal function and display that same modal popin.
Can anyone help me?
Here is the modal code:
function modalpopin() {
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
<!-- Trigger/Open The Modal -->
<div id="myBtn">Open Modal</div>
<!-- The Modal -->
<div id="myModal" >
<!-- Modal content -->
<div >
<span >×</span>
<p>Some text in the Modal..</p>
</div>
</div>
This is the second script I tried. I want this to open the same modal popin. It does not seem to work...
$("#modal-popin").click(function() {
modalpopin();
});
<div id="modal-popin">Click Here to open the Modal</div>
CodePudding user response:
Getting DOM elements using $("selector")
is jQuery syntax, a library that you do not seem to use (it's not included in the JSFiddle).
Use vanilla JS:
document.getElementById("myBtn").addEventListener("click", function(event) {
modalpopin();
});
edit: jQuery is actually in the JSFiddle, my bad
CodePudding user response:
Try this -
$( "#modal-popin" ).on( "click", function( event ) {
modalpopin();
});