I've developed a script
which acts as a modal trigger.
What it does is: whenever a user clicks on an element with the class "toggle-feature"
it'll open activate a modal (from which the element has specified via data-toggle
).
For example, if I click:
<button class="toggle-feature" data-toggle="random-modal" data-class="custom-class">Test</button>
It should add the class "custom-class"
to this element:
<div id="random-modal">Random Modal</div>
So far, it works as semi-intended. However, if the element that is supposed to act as a "trigger" has children, and one of the children is clicked on, the modal won't activate.
I have tried so many approaches (which includes changing almost every line of code), along with e.stopPropagation()
and the use of document.querySelectorAll(".toggle-feature, .toggle-feature *")
- but none of them ever seemed to work.
This is my (simplified and prettied) JavaScript:
// globals
var regex;
// functionality
document.onclick = function(e){ // on document click
var tf = document.getElementsByClassName("toggle-feature");
e.stopPropagation(); // does not stop dom bubbling up
for(var i = 0; i < tf.length; i++){ // iterate through each toggle button
if(e.target == tf[i]){ // if the element clicked was one of the toggles
if(tf[i].hasAttribute("data-toggle")){ // if the element has specified a modal to togal
var modal = document.getElementById(tf[i].getAttribute("data-toggle")); // get the specified modal
regex = new RegExp("(?:^|\\s)" + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active") + "(?!\\S)"); // some regex for targeting a specific class
if(modal.className.match(regex)){ // if the modal has the "active" class
modal.className = modal.className.replace(regex, ""); // remove the class
} else { // vice versa
modal.className = modal.className + " " + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active");
}
}
}
}
}
Here is the JsFiddle for it (along with all the original JS, and an example): https://jsfiddle.net/n8t6u4s6/