wss web
wss web

Reputation: 13

How to add/remove a background color using jQuery and html5 data attributes

I am trying to add an unique background color to the label of check boxes when they are clicked (the check boxes themselves are hidden). I can get it to add the background color but it will not remove it once it is applied. What I have (https://jsfiddle.net/9oq88dro/):

CSS

label {user-select:none}
input {position: absolute; left: -9999px;}

HTML

<div class="container">
  <input id="1" type="checkbox" value="test 1"><label for="1" data-color="red">test 1</label>
  <input id="2" type="checkbox" value="test 2"><label for="2" data-color="blue">test 2</label>
  <input id="3" type="checkbox" value="test 3"><label for="3" data-color="green">test 3</label>
</div>

jQuery

$('.container label').on('click', function() {
  if ($(this).css('background-color', '')) {
    $(this).css('background-color', $(this).data("color"));
  } else {
    $(this).css('background-color', '');
  }
});

Upvotes: 1

Views: 2655

Answers (2)

Michael Coker
Michael Coker

Reputation: 53674

Some browsers will return background-color in rgb() and rgba(), not necessarily the color name you've given it. If you just want to toggle the color on and off, you could toggle a class to determine the state.

$('.container label').on('click', function() {
  var color = $(this).data('color');
  if (!$(this).hasClass('color')) {
    $(this).css('background-color', color);
    $(this).addClass('color');
  } else {
    $(this).css('background-color', 'transparent');
    $(this).removeClass('color');
  }
});
label {
  user-select: none
}

input {
  position: absolute;
  left: -9999px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <input id="1" type="checkbox" value="test 1">
  <label for="1" data-color="red">test 1</label>
  <input id="2" type="checkbox" value="test 2">
  <label for="2" data-color="blue">test 2</label>
  <input id="3" type="checkbox" value="test 3">
  <label for="3" data-color="green">test 3</label>
</div>

Upvotes: 2

Taplar
Taplar

Reputation: 24965

Looks like css was returning rgba(0, 0, 0, 0). You could use just the dom properties if you wanted though.

$('.container label').on('click', function() {
  if (!this.style.backgroundColor) {
    this.style.backgroundColor = $(this).data("color");
  } else {
    this.style.backgroundColor = '';
  }
});
label {user-select:none}
input {position: absolute; left: -9999px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <input id="1" type="checkbox" value="test 1"><label for="1" data-color="red">test 1</label>
  <input id="2" type="checkbox" value="test 2"><label for="2" data-color="blue">test 2</label>
  <input id="3" type="checkbox" value="test 3"><label for="3" data-color="green">test 3</label>
</div>

Upvotes: 0

Related Questions