dhaliman dhaliman - 6 months ago 7
jQuery Question

How to toggle the background colour of a div element using jQuery?

I am trying to toggle the background colour of a div element but my code doesn't work. I wrote the following code:

$(document).ready(function(){
var $on_off = true;
$('div.hot').on('click', function($on_off){
if($on_off){
$(this).css('background-color', 'red');
}
else{
$(this).css('background-color', 'yellow');
}
$on_off = !$on_off;
});
});


I don't understand why this wouldn't work.
Thanks!

Answer

Remove argument from on handler as first argument is event-object which is always evaluated as true(Boolean({})===true)

$(document).ready(function() {
  var $on_off = true;
  $('div.hot').on('click', function() {
    if ($on_off) {
      $(this).css('background-color', 'red');
    } else {
      $(this).css('background-color', 'yellow');
    }
    $on_off = !$on_off;
  });
});

Simplified code:

$(document).ready(function() {
  var $on_off = true;
  $('div.hot').on('click', function() {
    $(this).css('background-color', $on_off ? 'red' : 'yellow');
    $on_off = !$on_off;
  });
});