Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
James 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!!