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

JavaScript

Simplify 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

  1. 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 ?

  1. how to prevent the body from scrolling when the div is block ?

Thank you in advance !

1 Answer

Steven Parker
Steven Parker
243,318 Points

Congrats on the job. :+1:

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

Hey Steven, thanx for a tip !!!