I'm using jQuery to select a button on my website and add an event listener to add a night-time
class when it is clicked.
Initially the button works, however when I click the button again it won't run the code to remove the night-time
class.
Here is the JavaScript code:
var night_time = false;
if (!night_time) {
$('.blog-desc').find('a').on('click', function() {
$('html').addClass('night-time').animate(200);
night_time = true;
console.log("Making it night!");
});
} else {
$('.blog-desc').find('a').on('click', function() {
$('html').attr('class', "");
night_time = false;
console.log("Making it day!");
});
}
I really don't know why this isn't working, but I feel like I'm missing something painfully obvious. Also, the .animate({}, 200)
isn't working either, as it just instantly applies the class, but this problem isn't as important to me as the main one.
Updating your night_time
variable won't automagically change the event handler.
Try this instead:
var night_time = false,
$html = $('html');
$('.blog-desc').find('a').on('click', function() {
night_time = !night_time;
$html.toggleClass('night-time', night_time);
console.log(night_time ? "Making it night!" : "Making it day!");
});
var night_time = false,
$html = $('html');
$('.blog-desc').find('a').on('click', function() {
night_time = !night_time;
$html.toggleClass('night-time', night_time);
console.log(night_time ? "Making it night!" : "Making it day!");
});
.night-time {
background: #000;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blog-desc">
<a>Click me</a>
</div>
From you code what I understand is you want to toggle the presents of the class night-time
$('.blog-desc').find('a').on('click', function () {
$('html').toggleClass('night-time');
});
If you want to do something else depending on the state(night/day) you can test for the presents of the class
$('.blog-desc').find('a').on('click', function () {
var $html = $('html').toggleClass('night-time');
if ($html.hasClass('night-time')) {
console.log('now it is night')
} else {
console.log('now it is day')
}
});
In your code the problem is the if
condition is evaluated only once when the page is loaded then since the default value is false
the if
block is executed and addClass()
callback is executed, the second handler is not registered at all.
If for any reason you want to check a case like this you need to have a single click handler and check the condition within the click handler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With