Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript if/else not acting as expected

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.

like image 923
Zach Avatar asked Dec 03 '22 17:12

Zach


2 Answers

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>
like image 178
Oriol Avatar answered Dec 05 '22 06:12

Oriol


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

like image 38
Arun P Johny Avatar answered Dec 05 '22 06:12

Arun P Johny