Jump to content

w3.css, need modification to close dropdown when clicked outside of it


Prednisolon

Recommended Posts

Hi everybody,

I am new here and just discovered w3.css
I've been building websites with Bootstrap for many years, but w3.css seems to be a much smaller and sleeker alternative without some of the overhead.

One of the most important parts for me is the navigation. It needs to work on every device and absolutely has to be accessible as per WCAG2.0.

The w3.css thankfully has the option of "w3-dropdown-click" instead of opening it by hover.
So far so good, but the dropdown only closes if I click on the same button again, or on one of the options in the dropdown.

I need it to close also, when I click outside of it though.

Here is the code (taken from the demo templates):

function myFunction() {
    close_on_bg_click: true;
    var x = document.getElementById("Demo");
    if (x.className.indexOf("w3-show") == -1)
        x.className += " w3-show";
    else
        x.className = x.className.replace(" w3-show", "");
    }

Can somebody please modify this, so the dropdown closes if I click elsewhere? Either on another dropdown, or just on the Body.


I already found a modification that uses

<body onclick="myFunction()">

and it works, but is bad practise. I am looking for a solution inside the script, without having to change the BODY tag.
Vanilla JS only please, no JQuery.

Maybe somebody even has a fully formed navigation with dropdowns, including ARIA tags as well?

Cheers and thanks.

Edited by Prednisolon
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...