Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  200] [ 3]  / answers: 1 / hits: 58463  / 9 Years ago, wed, january 13, 2016, 12:00:00

I have a page that needs to have different modal boxes open when their corresponding link on the page is clicked. I've got the structure and javascript to work for ONE window, but I can't get it to work for more than one. I am thinking I need to loop through each modal box...but can't quite figure out the syntax.



This is for a client's WordPress site, and I'm using Advanced Custom Fields to populate the content. The page isn't published yet, so here's a codepen that shows my code: http://codepen.io/FelixB/pen/EPvEVG



The code:



var modal = document.getElementsByClassName('modal-window');

var btn = document.getElementsByClassName(click-to-open);

var span = document.getElementsByClassName(close)[0];

for (var i = 0; i < btn.length; i++) {
var thisBtn = btn[i]
thisBtn.onclick = function() {
alert(hello);

//modal.style.display = block;
}
}

span.onclick = function() { 
modal.style.display = none;
}

window.onclick = function(event) {

}

More From » wordpress

 Answers
43

You must make modals unique to be able to select them later. One way to do this is through id.



<div id=modal-window-one class=modal-window modal></div>
<div id=modal-window-two class=modal-window modal></div>


You need to define which button which window should open. One possible solution for this is through data-attributes



<div class=click-to-open data-modal=modal-window-one> //will open modal one
<div class=click-to-open data-modal=modal-window-two> //will open modal two


And then - event:



var btn = document.getElementsByClassName(click-to-open);

for (var i = 0; i < btn.length; i++) {
var thisBtn = btn[i];
thisBtn.addEventListener(click, function(){
var modal = document.getElementById(this.dataset.modal);
modal.style.display = block;
}, false);


Again - this is one possible solution.


[#63742] Monday, January 11, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;