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!
Remove argument from
on
handler as first argument isevent-object
which is always evaluated astrue
(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;
});
});
Event handlers receives an Event Object when they are invoked but you are expecting another variable ( $on_off
) which doesn't exist inside event handler. So $on_off
variable that you have passed to event handler is in fact an object which will be automatically created and passed to the event handlers when they are invoked. This object is commonly referred to as event
or e
. This object contains necessary information about event that is actually happened. To use $on_off
variable you don't need to pass it to event handler explicitly.
$(document).ready(function(){ var $on_off = true; $('div.hot').on('click', function(event){ event.preventDefault(); if($on_off){ $(this).css('background-color', 'red'); } else{ $(this).css('background-color', 'yellow'); } $on_off = !$on_off; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="hot">Click Me</div>
I think this will be better served if you add two classes red
and yellow
$(document).ready(function() {
$('div.hot').on('click', function() {
if($(this).hasClass('red')
$(this).switchClass('red','yellow');
else
$(this).switchClass('yellow','red');
});
});
and just initialise your div with
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.