bastiag5
bastiag5

Reputation: 166

Remove and restore styles on click

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

Upvotes: 1

Views: 118

Answers (1)

Saeed Shamloo
Saeed Shamloo

Reputation: 6574

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:

const items = $('.item');

function toggleFilter(button, relevantIndexes) {
  const toggleOn = button.attr('data-toggle') == 'on'
  button.attr('data-toggle', toggleOn ? 'off' : 'on')

  $.each(items, function(index, item) {
    if (!relevantIndexes.includes(index)) return;
    const style = item.getAttribute('style');
    if (toggleOn) {
      item.removeAttribute('style');
    } else {
      item.setAttribute('style', 'filter:grayscale(100%)');
    }
  });
}

$('#btn-limone').on('click', function() {
  const relevantIndexes = [0, 1, 3];
  toggleFilter($(this), relevantIndexes);
});

$('#btn-lime').on('click', function() {
  const relevantIndexes = [1, 2, 3];
  toggleFilter($(this), relevantIndexes);
});
.item {
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="item">
    <img src="https://fakeimg.pl/200x100/a10000/?text=Lemone" />
  </div>
  <div class="item">
    <img src="https://fakeimg.pl/200x100/a10000/?text=Lemone-Lime" />
  </div>
  <div class="item">
    <img src="https://fakeimg.pl/200x100/a10000/?text=Lime" />
  </div>
  <div class="item">
    <img src="https://fakeimg.pl/200x100/a10000/?text=Lemone-Lime" />
  </div>
</div>

<button class="btn" id="btn-limone" data-toggle="off">Limone</button>
<button class="btn" id="btn-lime" data-toggle="off">Lime</button>

Upvotes: 1

Related Questions