shokis
shokis

Reputation: 71

How to reset SVG color on second click

I am using this to fill an svg on click :

jQuery('#color-my-svg').on("click", function() {
    jQuery('#color-my-svg').css({ fill: "#ff0000" });

which is the simplest way to have the color reset to default when a user clicks the button the second time?

Upvotes: 1

Views: 236

Answers (3)

Asfan Shaikh
Asfan Shaikh

Reputation: 769

This code might be helpful...

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: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The simplest way to achieve this would be to set the fill with a CSS class, then toggle that class on click:

$('#color-my-svg').on("click", function() {
  $(this).toggleClass('foo');
});
svg rect {
  fill: #CCC;
}
.foo {
  fill: red; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg>
  <rect id="color-my-svg" x="10" y="10" width="100" height="100" stroke="black" />
</svg>

Upvotes: 2

satish mallick
satish mallick

Reputation: 794

Try This:-

var change_color = 0;
jQuery('#color-my-svg').on("click", function() {
if(change_color==0){
    jQuery('#color-my-svg').css({ fill: "#ff0000" });
    change_color = 1;
    }
else{
jQuery('#color-my-svg').css({ fill: "blue" });
    change_color = 0;
}    

Upvotes: 0

Related Questions