I want the fill color of this SVG icon to change once I click on it and change back when I click on it again. How do I do this? I preferably want to do this using Javascript.
.remove svg{ fill: gray; opacity: 0.8; height: 50px; width: 45px; } .remove svg:hover{ fill: red; opacity: 0.7; transition-duration: 0.3s; } button{ appearance: none; width: 47.5px; height: 50px; box-sizing: border-box; position: relative; background: white; border: none; cursor: pointer; }
<button class="remove"> <svg version="1.1" id="Capa_1" id="removeB" class="removeB" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 328.51 328.51" style="enable-background:new 0 0 328.51 328.51;" xml:space="preserve"> <polygon points="229.044,88.858 164.255,153.647 99.466,88.858 88.858,99.466 153.647,164.255 88.858,229.044 99.466,239.651 164.255,174.862 229.044,239.651 239.651,229.044 174.862,164.255 239.651,99.466"/> </svg> </button>
I modified your CSS codes by only adding "clicked" class and I also wrote a simple JS script. Here is how you can do this by JS:
.remove svg{
fill: gray;
opacity: 0.8;
height: 50px;
width: 45px;
}
.remove.clicked svg{
fill: red;
opacity: 0.7;
transition-duration: 0.3s;
}
button{
appearance: none;
width: 47.5px;
height: 50px;
box-sizing: border-box;
position: relative;
background: white;
border: none;
cursor: pointer;
}
var button = document.querySelector("button"); button.addEventListener("click", function(){ this.classList.toggle("clicked"); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.