3

I have an event listener that I'm trying to toggle between a class (which is working) and a data-selection attribute of true/false (which is not). I have the data-selection attribute for div class="dice" already set to false by default.

game.selection = function() {
  $(".dice").on("click", function() {
    $(this).toggle(function () {
      $(this).attr('data-selection', true);
    });
    $(this).toggleClass("active");
  }); 
};
2
  • I fiddled with the code more and got it to KIND of work: $(".dice").on("click", function() { if ($(this).attr('data-selection', false)) { $(this).attr('data-selection', true); } $(this).toggleClass("active"); }); The issue with this now is it changes the data-selection to true when clicked, but does not toggle back to false when clicked a second time. Commented Mar 29, 2016 at 2:38
  • $(this).attr('data-selection', $(this).attr('data-selection')=="false"); Commented Mar 29, 2016 at 2:39

3 Answers 3

2

Replace :

$(this).toggle(function () {
  $(this).attr('data-selection', true);
});

by :

$(this).attr('data-selection', ($(this).attr('data-selection') == "false" ? true : false));
Sign up to request clarification or add additional context in comments.

2 Comments

$(this).attr('data-selection', ($(this).attr('data-selection') == "false" ? true : false)); is same as $(this).attr('data-selection', $(this).attr('data-selection')=="false"); which is commented above :)
I agree, I saw you comment after posting my answer. (It was not there when I started writing it)
0

It is better if you use data() function instead of attr(). Also you can reduce the code to this.

$(this).data('selection', ! $(this).data('selection'));

2 Comments

if he set the data using .attr() will using .data() work?
@guradio no. it will not.
0

When you pass in two parameters to .attr(attributeName,value), the second param sets the value. You could write a custom extension, similar to toggleClass to conditionally add or .removeAttr() like this:

(function($) {
    $.fn.toggleAttr = function(attributeName, state) {
        return this.each(function() {
           if (state) {
             $(this).attr(attributeName,"")
           } else {
             $(this).removeAttr(attributeName)
           }
        });
    };
}(jQuery));

Then use like this:

$(".class").toggleAttr("boolAt", false);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.