How to call javascript function on all elements with the same classname - javascript

I am trying to get a pop-up window to display when a user clicks on an element on my page. I have all the functionality for the pop-up working correctly; however, I am having trouble getting the function to pop-up for every element that matches the specified classname. My code is below:
<script>
function descPop () {
// Description pop-up
// Get the modal
var modalprod = document.getElementById('myModalTwo');
// Get the button that opens the modal
var btnprod = document.getElementsByClassName("add-but")[0];
// Get the <span> element that closes the modal
var spanprod = document.getElementsByClassName("prod-close")[0];
// When the user clicks on the button, open the modal
btnprod.onclick = function() {
modalprod.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
spanprod.onclick = function() {
modalprod.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalprod) {
modalprod.style.display = "none";
}
}
}
</script>
Now, I know that currently this code is assigning index 0 to var btnprod; therefore, it will only pop-up when you click on the first element which matches the classname "add-but". How do I assign and access all elements, so that every tag with the classname "add-but" will pop-up the window?
Thanks
Solution:
function descPop () {
// Description pop-up
// Get the modal
var modalprod = document.getElementById('myModalTwo');
// Get the button that opens the modal
var btnprod = document.getElementsByClassName("add-but");
// Get the <span> element that closes the modal
var spanprod = document.getElementsByClassName("prod-close");
// When the user clicks on the button, open the modal
for (var i = 0; i < btnprod.length; i++) {
btnprod[i].onclick = function() {
modalprod.style.display = "block";
}
}
// When the user clicks on <span> (x), close the modal
for (var i = 0; i < spanprod.length; i++) {
spanprod[i].onclick = function() {
modalprod.style.display = "none";
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalprod) {
modalprod.style.display = "none";
}
}
}

If Jquery is not an option, you could iterate over the HtmlCollection to do it:
var btnprod = document.getElementsByClassName("add-but"); // <- this gives you a HTMLCollection
for (var i = 0; i < btnprod.length; i++) {
btnprod[i].onclick = function() {
modalprod.style.display = "block";
}
}

you can change your code to the following:
$('.add-but').on('click', function() {
$(this).css('display', "none");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-but">
fafafafafa
</div>
<br>
<div>
fafafaffafafaafafa
</div>
<br>
<div class="add-but">
fafafafafafafaafafafaffafa
</div>
note that i have changed the display to none instead of block for this example.
this uses the jQuery selectors, event binding and css function.

I'd prefer that sexier solution:
document.getElementsByName('add-but').forEach(btn => {
btn.onclick = (e) => {
btn.style.display = "block"
}
});
Same in one line:
document.getElementsByName('add-but').forEach(btn => btn.onclick = (e) => btn.style.display = "block" );
If you want have multiples clicks events on same btn:
document.getElementsByName('add-but').forEach(btn => btn.addEventListener('click', e => btn.style.display = "block" ));

You've added a jquery tag but there's no jquery here. With jquery you can just write:
$('.classname').on ('click', function () {
//activate modal
});
Alternatively, you can add them to a variable as a collection, referencing this variable will apply to any element with this class.
var x = $('.classname');

Related

Direct link to a modal window doens't work

For this webpage: https://www.wonderewereldvan.be/VakantieinBelgie/KalenderTest2.html I would like have a direct link to a modal popup.
Off course I searched Stackoverflow for possible solutions, and I tried several ones. However when using https://www.wonderewereldvan.be/VakantieinBelgie/KalenderTest2.html#myModal it doesnt't open the modal window.
The last piece of code I tried was
function popModal() {
// code to pop up modal dialog
}
var hash = window.location.hash;
if (hash.substring(1) == 'myModal') {
popModal();
}
Those are the details of the popup:
<div class="modal" id="myModal">
The code I found on W3Schools
<script>
// 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";
}
}
</script>
Many thanks in advance for your help!
You can put the existing code into an event handler named hashchange :
window.addEventListener("hashchange", () => {
var hash = window.location.hash;
if (hash.substring(1) == "myModal") {
popModal();
}
});
Read more about this handler in MDN hashchange

Hide 'close' links when modal is not open

Ive been working on this for hours, I've tried vars, I tried hiding elements, and nothing is working and and and.. sorry for the exitement, but I'm almost down to the end,
the issue:: I have a basic javascript modal, taken from w3 schools, which has been altered slightly per my needs,
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal
my javascript code is below.
What I need is, I need to hide the CLOSE span when the modal pop up is hidden,
<span class="close">CLOSE</span>
in other words, I dont want the close link showing at all times, thw close link should be hidden when modal os closed, and showing when modal is open.
here is my code below, can I please get a working javascript example.
Any help would be greatly appreciated
function closeModal() {
modal.style.display = "none";
}
// 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 spans = document.getElementsByClassName("close");
for (let closeBtn of spans) {
closeBtn.onclick = closeModal;
}
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>```
If I understand you correctly.
Try this:
function closeModal() {
modal.style.display = "none";
for (let closeBtn of spans) {
closeBtn.style.display = 'none';
}
}
// 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 spans = document.getElementsByClassName("close");
for (let closeBtn of spans) {
closeBtn.onclick = closeModal;
closeBtn.style.display = 'none';
}
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
for (let closeBtn of spans) {
closeBtn.style.display = 'inline';
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
for (let closeBtn of spans) {
closeBtn.style.display = 'none';
}
}
}
</script>```
It would be better if we put out the repeating code in separate functions.
Just add to your show/hide function appropriate hide/show span:
Change closeModal() to:
function closeModal() {
modal.style.display = "none";
spans[0].style.display = "block";
}
and change btn.onclick to:
btn.onclick = function() {
modal.style.display = "block";
spans[0].style.display = "none";
}
I see you are using getElementsByClassName() which is returning (always) array of results (thats why I'm using index ([0]) to access found element). If I were you I would add new id to the span so you can be sure what you target.
Have a look at Changing HTML style

How do i open the modal div with the corresponding ID?

I have a page with multiple modals, when i click a button for one of these modals, the first always opens. The code used to work with Bootstrap 4.0, but I switched from bootstrap to Tailwind CSS.
The modal div has id="modal1".
The button has class="modal-open" and data-target="#modal1".
This is my javascript code:
var openmodal = document.querySelectorAll('.modal-open')
for (var i = 0; i < openmodal.length; i++) {
openmodal[i].addEventListener('click', function(event){
event.preventDefault()
toggleModal()
})
}
const overlay = document.querySelector('.modal-overlay')
overlay.addEventListener('click', toggleModal)
var closemodal = document.querySelectorAll('.modal-close')
for (var i = 0; i < closemodal.length; i++) {
closemodal[i].addEventListener('click', toggleModal)
}
document.onkeydown = function(evt) {
evt = evt || window.event
var isEscape = false
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc")
} else {
isEscape = (evt.keyCode === 27)
}
if (isEscape && document.body.classList.contains('modal-active')) {
toggleModal()
}
};
function toggleModal () {
const body = document.querySelector('body')
const modal = document.querySelector('.modal')
modal.classList.toggle('opacity-0')
modal.classList.toggle('pointer-events-none')
body.classList.toggle('modal-active')
}
When I click the button with data-target="modal3", I want modal 3 to open, now modal 1 always opens.
const modal = document.querySelector('.modal')
This line will always return the first occurrence of class 'modal', thus modal 1, assuming it comes first in the markup. If you want toggleModal() to operate on another div, you will have to pass the ID of the div as an argument to toggleModal().
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Add a variable from a Post ID within a loop to a Modal Query getElementByID

I have a page which has 2 (but the potential of many many more) buttons which open up modal windows, each modal has a form and some text on it which is individual to that button.
All of these items are called from a Custom Post Type from within WordPress.
The issue I'm having is that I'm currently using a Modal Window JS and CSS:
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";
}
}
Then it's using the usual to open have the details for the Modal within the loop for the item on my page.
My issue is, is that the id is individual, so it only works once. I need to find a way to allow for a post_ID from the loop to be involved in the opening. I have tried adding "> and then changing out the var modal = document.getElementByID('myModal'); to document.querySelector("[id^='myModal-']"); but this didn't work.
The code is currently being used here: https://www.ubersmith.com/webinars-and-events/
You will see that the first "On Demand" link works but the second doesn't.
Can anyone help me work this out? I'm sure that I'm just missing one bit of the puzzle.
Any help would be great!
Thanks in advance :)
Your problem is that document.getElementById and document.querySelector will only ever get one element. Instead, change the modal and button ids to a class-name, say modal and modal-trigger. Then, find all of the article elements, and add the event listeners in a loop. For example,
var articles = document.querySelectorAll("article");
for (var i = 0; i < articles.length; i++) {
var article = articles[i];
var modal = article.querySelector(".modal");
var button = article.querySelector(".modal-trigger");
var closeButton = article.querySelector(".close");
// if there is no modal, ignore this article
if (!modal) continue;
button.onclick = function() {
modal.style.display = "block";
}
closeButton.onclick = function() {
modal.style.display = "none";
}
// add event listener instead so it can be added multiple times
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
}
Thanks Jay :) I took what you did and found the solution:
var modalBtns = [...document.querySelectorAll(".register")];
modalBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.getAttribute('data-modal');
document.getElementById(modal).style.display = "block";
}
});
var closeBtns = [...document.querySelectorAll(".close")];
closeBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.closest('.modal');
modal.style.display = "none";
}
});
window.onclick = function(event) {
if (event.target.className === "modal") {
event.target.style.display = "none";
}
}
This did the job :)
Thanks for your help :)

Passing a variable to jQuery function

I know this is probably simple but I have read and tried a bunch of answers on here and I cannot figure it out. How do I pass the variable 'booklink' to the jQuery function?
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btns = document.querySelectorAll('.ebtn');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
[].forEach.call(btns, function(btn) {
btn.onclick = function(event) {
modal.style.display = "block";
var booklink = jQuery(this).attr("data-id");
console.log(booklink);
// on submit open book link
jQuery('#mc4wp-form-1').submit(function () {
window.open(booklink);
})
}
})
// 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";
}
}
From what I can see you are using a mix of jQuery and vanilla javascript, this is not a bad thing but it can make things confusing in the future, try to stick to one style (i.e. jQuery OR vanilla javascript NOT both).
From what I can see from your code, your code should work as is since you're declaring the 'booklink' variable before the submit is called.
I've gone ahead and tidied up your code to match all jQuery and modified it slightly which should assist in passing the 'booklink' value.
// Get the modal
var modal = jQuery("#myModal");//return matching elemetns id(s) of #myModal
// Get the button that opens the modal
var btns = jQuery('.ebtn');//return matching elements with class(es) of .ebtn
//Declare booklink out of the event
var booklink = "";
$('.ebtn').on('click', function(event){
modal.css('display','block');
//Update booklink when processing the click event
booklink = jQuery(this).attr("data-id");
//Call the function to submit the form and open a new window
openBookLink(booklink);
});
// When the user clicks on <span> (x), close the modal
$('.close').on('click', function(){
modal.css('display','none');
})
// When the user clicks anywhere outside of the modal, close it
$(window).on('click', function(event) {
if (event.target == modal) {
modal.css('display','none');
}
});
function openBookLink(booklink){
jQuery('#mc4wp-form-1').submit(function () {
//This should match what booklink was set to above
window.open(booklink);
})
}
The main changes are declaring the booklink variable outside of the event and defining it's value when you process the click event, which it's then passed to a function.

Categories

Resources