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).

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


<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>
<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");
        }
        

Loading...

About Author

Loading...

Loading...

👨‍💻

Frontend development

Learn frontend development with examples and practical exercise of HTML,CSS,JS,React.js.