Today I got some problems changing the attributes of a svg with js using the onclick
method;
here is what i want to do:
here is what I did:
(there is the arrow, but the grey covers it)
Here is my code:
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
CodePudding user response:
With document.getElementById("arrow")
you are searching the <svg>
element.
Then you are changing its fill
attribute, but the fill
attribute of the <path />
element overwrites it. So you have to either move id="arrow"
from the <svg>
to the path
move the fill
from the <path />
to the <svg>
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path id="arrow" fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
or
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13" fill="#6E8098">
<path
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
CodePudding user response:
I'd recommend using a CSS class and then using classlist.toggle
to move it onclick:
function social() {
document.getElementById("arrow").classList.toggle('active');
}
.active {
background: grey;
border-radius: 30px;
padding: 10px;
}
.active > path {
fill: white;
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path id='path' fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>