Reputation: 111
I followed the w3schools tutorial for modals https://www.w3schools.com/howto/howto_css_modals.asp but when i click on the button, nothing happens. I've actually followed two previous modal tutorials and on each one, nothing happens when i click the button. I've checked that the external js file is working.
$(window).on('scroll', function() {
if ($(window).scrollTop()) {
$('nav').addClass('black');
} else {
$('nav').removeClass('black');
}
})
$(document).ready(function() {
$(".menu h4").click(function() {
$("nav ul").toggleClass("active")
})
})
//modal
var modal = document.getElementsByClassName('modal-container');
// Get the button that opens the modal
var btn = document.getElementsByClassName("modal-btn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");
// When the user clicks the button, open the modal
btn.onclick = function() {
modal[0].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";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="modal-btn"> Click me</button>
<div class="modal-container">
<div class="modal-content">
<span class="close">×</span>
<p> Some text in modal</p>
</div>
</div>
Upvotes: 0
Views: 89
Reputation: 1805
getElementsByClassName returns an object (NodeList) that resembles an array, and doesn't return a single element as you were expecting
getElementById returns a single element, and that's what you should be using for a modal
$(window).on('scroll', function() {
if ($(window).scrollTop()) {
$('nav').addClass('black');
} else {
$('nav').removeClass('black');
}
})
$(document).ready(function() {
$(".menu h4").click(function() {
$("nav ul").toggleClass("active")
})
})
//modal
var modal = document.getElementsByClassName('modal-container')[0];
// Get the button that opens the modal
var btn = document.getElementsByClassName("modal-btn")[0];
// 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";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="modal-btn"> Click me</button>
<div class="modal-container">
<div class="modal-content">
<span class="close">×</span>
<p> Some text in modal</p>
</div>
</div>
Upvotes: 1