Javascript fills different svg forms at once
I am looking for a solution to fill different svg forms in one click.
As you can see, there are two main svg forms with some subforms. What I want to do is to fill all the subforms of one full form when I only click one of the subforms. Each path has its own identifier, similar. In an example case, these are 1_7- {b, p, d, m, o} and 1_6- {b, p, d, m, o}.
So, if I press either b, p, d, m, o from 1_7, I want the entire 1_7 to turn red.
The only problem (I think) is that I don't know how to subtract information about whether I pressed 1_7 or 1_6 from this.id when the javascript function is executed.
I think all of this will be added in
elem.onclick = function() {
source to share
I would suggest giving them a class or set of classes to identify them and populating all the elements that match the selector (eg ".1_7" or ".1_6"). Here's a function that could do it:
var fillBySelection = function(selector, color) {
var elems = document.querySelectorAll(selector);
for(var i=0; i<elems.length; i++) {
elems[i].style.fill = color;
}
}
If you keep the svg forms defined as they are, all siblings, you can fill in all siblings with the same color. Here is a violin that does it .
The fillByChildren function will look like this, you pass it this.parentNode
and the css color:
var fillChildren = function(element, color) {
var children = element.children;
for(var i=0; i<children.length; i++) {
children[i].style.fill = color;
}
}
source to share
You can pass the parent node using parentNode
to this
and then change the style on the child nodes.
var forms = document.getElementsByTagName("path");
for (var a = 0; a < forms.length; a++) {
var elem = forms[a];
elem.onclick = function() {
var nodes = this.parentNode.childNodes
for(var n in nodes){
if (nodes[n].tagName ==="path"){
if (nodes[n].style.fill=='rgb(255, 0, 0)') {
nodes[n].style.fill = '';
} else {
nodes[n].style.fill = 'red';
}
}
}
return false;
};
}
source to share
You can use silblings for this. I tried this
JSFiddle elem.onclick = function () {
var first = this.parentNode.firstChild;
var check = this.style.fill=='rgb(255, 0, 0)';
for ( ; first; first = first.nextSibling ) {
if ( first.nodeType === 1 ) {
if (check) {
first.style.fill = '';
} else {
first.style.fill = 'red';
}
}
}
return false;
};
source to share