Close dropdown menu after click outside of navbar using only JavaScript?


Close dropdown menu after click outside of navbar using only JavaScript?



I want to make a drop-down menu which one is very simple and when after click outside of nav its automatically hide. note I already make drop-down menu but... I don't understand how to close it. here is my HTML and javascript code.




<section class="dropdownone">


Dropdown One




  • Click Dropdown


    • home

    • about

    • profile




  • </section>





    Possible duplicate of How do I detect a click outside an element?
    – Lars-Olof Kreim
    Jul 3 at 7:58





    write an event that checks if the select dropdown is out of focus, ie, it is blurred, you need to write a blur event, when that event is fired, hide the dropdown menu.
    – Code_Ninja
    Jul 3 at 8:14




    2 Answers
    2



    Using JavaScript :




    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    .dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    }

    .dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
    }

    .dropdown {
    position: relative;
    display: inline-block;
    }

    .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    }

    .dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    }

    .dropdown a:hover {background-color: #ddd;}

    .show {display: block;}
    </style>
    </head>
    <body>

    <h2>Clickable Dropdown</h2>
    <p>Click on the button to open the dropdown menu.</p>

    Popular posts from this blog

    api-platform.com Unable to generate an IRI for the item of type

    PHP contact form sending but not receiving emails

    Do graphics cards have individual ID by which single devices can be distinguished?