Home > OS >  Remove and restore styles on click
Remove and restore styles on click

Time:12-15

I need a button called #btn-limone to remove filter: "grayscale(100%)" on first click and on the second click to restore it. I need it to be done through styles and not classes. How can I do this?

jQuery("#btn-limone").on("click", function () {
  jQuery("#agrumi_box, #frutta_polpa_bianca_box, #limone_box").removeAttr("style");
});

With this I can remove the style but I would like that at the second click it would be brought back to 100%.

Thank you to anyone who wants to help me

CodePudding user response:

You can check it has style attribute or not, if id doesn't have you can add your style, if it has style you can remove it. like this:

jQuery('#btn-limone').on("click", function() {
  const target = jQuery('#target');
  const style = target.attr('style');
  if(style){
    target.removeAttr('style');
 }else {
  target.attr('style', "filter:grayscale(100%)")
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="filter:grayscale(100%)" id="target"> <img src="https://fakeimg.pl/200x100/ff0000/?text=Image1"/></div>
<button id="btn-limone">Toggle filter</button>

CodePudding user response:

jQuery("#btn-limone").on("click", function () {
  let style = jQuery("#agrumi_box").attr("style");
  if(typeof(style)!="undefined"){
    jQuery("#agrumi_box, #frutta_polpa_bianca_box, #limone_box").removeAttr("style");
  }
  else{
    jQuery("#agrumi_box").attr("style","color:red;")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id="btn-limone">Button</button>
<div id="agrumi_box" style="color: red;" > Div </div>

this way you can achieve the same, but this is not recommended as it make the code more mess.

  • Related