简体   繁体   中英

How to toggleoff/rehide div when it is trigged by onlick?

When I click on DIV 1, it shows the drop down. Now I want to hide the drop down when I click on default tab or click anywhere else on the page to toggle off the drop down menu. How I go about write the JavaScript code for this?

HTML

<div id="dropdown-container">
    <div id="default-tab" onclick="toggleMenu()"><a href="#">1</a></div>
        <ul id="dropdown">
            <li ><a href="#"><span class="current-browse">2</span></a>
                <ul class="dropdown-items">
                    <li class="dropdown-item"><a href="#">3</a></li>
                    <li class="dropdown-item""><a href="#">4</a></li>
                </ul>
            </li>
        </ul>
    </div>
</div>

Javascript

function toggleMenu() {
    var dropDown = document.getElementById('dropdown');    
    if(dropdown.style.display == "block") { 
         dropdown.style.display = "none";
    } else { 
         dropdown.style.display = "block";
    }
}

CSS for dropdown has the display: none;

LINK: http://stackoverflow.com/questions/321239/event-on-a-click-everywhere-on-the-page-outside-of-the-specific-div.

You could use one of the solutions from above link. All that you need is a way to add a handler to the onclick event of the document object.

Your code, already works fine when there is an onclick event on the DIV 1. Except that it doesnt work on the first click. So just add the following to ur markup, so that it works fine the first time too.

<ul id="dropdown" style="display:block;">

This article is an excellent explanation of the problem you are facing, and why the stopPropagation solution is a Bad Idea. Since you aren't using JQuery, what you want to do will look more like this:

document.onclick = function(event) {
  if (!event.target.closest('#dropdown-container')) {
    dropdown.style.display = "none";
  }
}

Drop that outside of your toggleMenu function and it should hide your menu whenever anything else on your page is clicked without creating unexpected behavior (bugs) for other libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM