Reputation:
I want to display black SVGs and when a user clicks on one of them, I want to swap it for another SVG. Could someone help me with this.
HTML Code:
<svg class = "hidden" onclick="changeImage()" ..... >
<svg class = "scrolling-icon2" .....>
Javascript Code:
<script>
function changeImage() {
if (document.getElementsByClassName("hidden")) {
document.getElementsByClassName("scrolling-icon2");
} else {
document.getElementById("hidden");
}
}
</script>
At the moment nothing is occuring with the function.
Upvotes: 0
Views: 1099
Reputation: 586
I'm assuming that you are trading out scrolling-icon2 and hidden to display / hide. In this case do this:
function changeImage() {
const img1 = document.getElementById('img1');
const img2 = document.getElementById('img2');
const hidden = 'hidden';
const display = 'scrolling-icon2';
if (img1.classList.contains('hidden')) {
// img1 is hidden
// displaying
img1.classList.add(display);
img1.classList.remove(hidden);
// hiding
img2.classList.add(hidden);
img2.classList.remove(display);
} else {
// img2 is hidden
// displaying
img2.classList.add(display);
img2.classList.remove(hidden);
// hiding
img1.classList.add(hidden);
img1.classList.remove(display);
}
}
.hidden {
display: none;
}
.scrolling-icon2 {
display: block;
}
<svg id="img1" class="hidden" onclick="changeImage()" width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
Sorry, your browser does not support inline SVG.
</svg>
<svg id="img2" class="scrolling-icon2" onclick="changeImage()" height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
Sorry, your browser does not support inline SVG.
</svg>
In this we use css to hide / display. In the JavaScript, we get the two elements and check to see if the first one is hidden. If so we display it and hide the other. In the other case (img1 is displayed) we do the opposite.
We display / hide them by trading out the classes (.remove(class) and .add(class)).
Upvotes: 1