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 trial
Igor Pavlenko
12,925 PointsSimplify my javascript code
hey community
I am currently working on my first project for real client (for money lol)
i have a small issue
there is a page with 6 menu divs each of them has a button and a hidden overlay with the content displayed in it
my challenges here are
-
i display the overlays with js:
const buttonAfternoonTea = document.getElementById('buttonAfternoonTea'); const divAfternoonTea = document.getElementById('overlay-afternoon-tea'); buttonAfternoonTea.addEventListener('click', () => { divAfternoonTea.style.display = 'block'; });
divAfternoonTea.addEventListener('click', () => { divAfternoonTea.style.display = 'none'; });
since i have 6 divs like that do i have to repeat the code for each one of them ? i feel like the for loop should do the job but can't structure how to implement it ?
- how to prevent the body from scrolling when the div is block ?
Thank you in advance !
1 Answer
Steven Parker
243,318 PointsCongrats on the job.
You should be able to simplify the button handling by using a single delegated handler to take care of all 6 buttons at once. You could use DOM traversal in the handler to activate different overlays.
And you can deactivate scrolling like this:
document.body.style.overflow = "hidden"; // disable scrolling
document.body.style.overflow = "auto"; // allow scrolling
Igor Pavlenko
12,925 PointsIgor Pavlenko
12,925 PointsHey Steven, thanx for a tip !!!