Rob
Rob

Reputation: 6380

Onclick toggle data attribute

Is it possible to toggle a data attribute (e.g data-equalizer-watch) on click using Jquery?

Here's the html:

<a class="accordion-expander" href="#" data-equalizer-watch>

So onclick I want it to look like this:

<a class="accordion-expander" href="#">

I know this is wrong but something along these lines:

$(".accordion-expander").click(function(e) {
  e.preventDefault();
  $(this).toggleData('equalizer-watch');
});

Upvotes: 0

Views: 982

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206131

.toggleData() is not a default jQuery method, so let's create one:

Than inside the mini-plugin use jQuery's removeAttr() and attr() methods.

$.fn.toggleData = function(dname) {
  var d = `data-${dname}`;
  return this.is(`[${d}]`) ? this.removeAttr(d) : this.attr(d,'');
};


$(".accordion-expander").click(function(e) {
  e.preventDefault();
  $(this).toggleData('equalizer-watch');
});
[data-equalizer-watch] { color: fuchsia; }
<a class="accordion-expander" href="#" data-equalizer-watch>CLICK ME</a>
<a class="accordion-expander" href="#">CLICK ME</a>


<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>

Upvotes: 0

Squidward Tentacles
Squidward Tentacles

Reputation: 900

Just set the data-equalizer-watch value to false with .data() method in JQuery to toggle it.

 $(this).data("equalizer-watch", false);

But if you want to delete it from the display, just do this:

$(this).removeAttr("data-equalizer-watch");

If you use .attr() method to change the value, the data is not rendered.You must set data attribut with .data() method to re-render it.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

To make this work you can toggle back and forth between attr() and removeAttr() method calls depending on whether the element has the attribute when clicked:

$(".accordion-expander").click(function(e) {
  e.preventDefault();
  var method = $(this).is('[data-equalizer-watch]') ? 'removeAttr' : 'attr';
  $(this)[method]('data-equalizer-watch', '');
});
a[data-equalizer-watch] {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="accordion-expander" href="#" data-equalizer-watch>
  foo
</a>

However it's not guaranteed that this logic would work as you require. It would depend on how the dependant logic accesses the attribute.

A much better solution would be to always include the data attribute on the element but have it's value as a boolean flag which you toggle, like this:

$(".accordion-expander").click(function(e) {
  e.preventDefault();
  var $el = $(this);
  $el.data('equalizer-watch', !$el.data('equalizer-watch'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="accordion-expander" href="#" data-equalizer-watch="true">
  foo
</a>

Upvotes: 1

Related Questions