Reputation: 71
I am trying to change the fill color on SVG on the second click, currently, am able to ad fill color on the first click, but I want the color to change/reset to default on second click; This is my current code:
jQuery('#color-my-svg').on("click", function() {
if(!jQuery(this)[0].hasAttribute('style')){
jQuery('#color-my-svg').css({ fill: "#ff0000" });
}
else{
jQuery(this).removeAttr('style');
}
});
Upvotes: 1
Views: 464
Reputation: 6368
You can set a click counter as a variable
& check add/remove a class depending on the number of clicks like so:
HTML:
<div id="divId" class="divClass">I'm a div!</div>
CSS:
/* Styling for demo only */
.divClass {
background: green;
color: white;
height: 100px;
width: 100px;
}
.svg-fill-color {
background: red;
/* Add fill here */
}
JavaScript:
let clickNumbers = 0;
jQuery('#divId').on("click", function() {
clickNumbers++;
if(clickNumbers % 2 == 0){
jQuery('#divId').addClass('svg-fill-color');
} else {
jQuery('#divId').removeClass('svg-fill-color');
}
});
You can check the sample code here.
Let me know, if that helps!
Upvotes: 0
Reputation: 380
Whenever the user clicks on the element:
Change fill color iff the element has the class identifier(say
click-one
).
Else add the class identifier.
jQuery('#color-my-svg').on("click", function() {
if(jQuery('#color-my-svg').hasClass("click-one"))
jQuery('#color-my-svg').css({ fill: "#ff0000" });
else
jQuery('#color-my-svg').addClass("click-one");
});
Upvotes: 1