loading

How to close the dropdown menu when clicking outside

Hi in this article we are going to see how to implement and close the dropdown menu when clicking outside of the dropdown menu or any other case when you want to close anything (div, popup, or dropdown).

How to implement close the dropdown menu when clicking outside

In the above image, there are two element
outside element
inside element

Now to click the event of an outside element you have to close/toggle the class of the inside element if the clicked target is not = inside element

For React


<div class="outside" onclick={e=>e.currentTarget==e.target?e.currentTarget.firstchild.classList.remove('active')}>
   <div class="inside">
       <button onclick={e=>{e.currentTarget.parentElement.classList.toggle("active")}}>menu<button>
   </div>
</div>

For HTML

<div class="acc">
                        <span class="title"> title here <span class="acc-btn">v</span></span>
                        <span class="body">
                            lorem epsum sit ammet.
                        </span>                        
                    </div>
        const acc = document.querySelector('.acc')
            document.onclick = (e) => {
                if (!e.target.matches('.acc-btn') && !e.target.parentElement.matches('.acc')) acc.classList.remove('active')
            }
        
        document.querySelector(".acc-btn").onclick = (e) => {

            acc.classList.toggle("active");
        }
        

About Author

x

Order for website design

Help :