Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJames Moran
7,271 PointsWhy does boolean switch not work (jQuery)?
I am setting a global boolean ('overlayVisible') to true when '.overlay' is clicked.
var overlayVisible = false;
// 1 Capture click (of last list item)
if (overlayVisible === false) {
$('li:last-child').click(function () {
// show the overlay
$('.overlay').show('fast');
overlayVisible = !overlayVisible;
});
}
However, when checking to see if 'overlayVisible' is true, the code never runs. (I never see the 'bang!' written out to the console)
// 3 When (last list item) clicked again
if (overlayVisible) {
console.log('bang!');
// hide overlay
$('li:last-child').click(function () {
console.log('hidden!');
// hide the overlay
$('.overlay').hide();
overlayVisible = false;
});
}
Why is this happening? Thank you.
1 Answer
Matt F.
9,518 PointsHi James,
I cannot be sure without the remainder of your code - but my suspicion is that your second block of code is executing on initialization - when overlayVisible is equal to false - therefore never running what is in your if block.
Try this instead:
// hide overlay
$('li:last-child').click(function () {
// 3 When (last list item) clicked again
if (overlayVisible) {
console.log('bang!');
console.log('hidden!');
// hide the overlay
$('.overlay').hide();
overlayVisible = false;
}
});
James Moran
7,271 PointsJames Moran
7,271 PointsThank you! It didn't work exactly as you put it, but I applied your method to the entire script and it worked!!