mardi 5 mai 2015

How to use Javascript to close css drop down menu on outside click?

I want to use pure javascript (not jquery) to close a pure css drop-down menu I have created when clicking outside of the menu. How can I do this?

HTML:

<ul>
    <div class="submenu">
        <ul></ul>
    </div>
    <div class="submenu">
        <ul></ul>
    </div>
</ul>

That's the basic structure of my HTML. I want to close the submenu if clicking outside of the submenu. Any way to do so with pure javascript? So far I've tried this:

Javascript:

        <script>
            document.onclick = closeMenu();
            function closeMenu() {
                document.getElementsByClassName("submenu").style.display = 'none';
            }
        </script>

This doesn't seem to work. Any ideas?

Aucun commentaire:

Enregistrer un commentaire