The CSS :hover
code works great for PC users, but I discovered that mobile users can't really use hover on links, so I am hoping to convert this CSS code to JavaScript or jQuery so that it works using the click event.
It is part of a multi-sub dropdown menu. I tried using toggle()
, but I had issues when there were other sub dropdowns.
This is a chunk of the HTML of the dropdown menu. When one sub dropdown opens, all other dropdowns should close.
.pages-links-sub div.dropdown-contentc {
display: none;
}
.columnb-sub>.pages-links-sub {
display: none;
}
.columnb-sub:hover>.pages-links-sub {
display: block;
div.dropdown-contentc {
display: block;
}
}
<div class="columnb">
<p class="pages-toptext">Standard Settings</p>
<div class="pages-links">
<a href="#">Link 1</a>
<div class="columnb-sub">
<a href="#">SubLinks 1 <i class="fa fa-caret-down"></i></a>
<div class="pages-links-sub">
<div class="dropdown-contentc">
<div class="columnb">
<a href="#">SubLink 1</a>
<a href="#">SubLink 2</a>
<a href="#">SubLink 3</a>
</div>
</div>
</div>
</div>
<div class="columnb-sub">
<a href="#">SubLinks 2 <i class="fa fa-caret-down"></i></a>
<div class="pages-links-sub">
<div class="dropdown-contentc">
<div class="columnb">
<a href="#">SubLink 1</a>
<a href="#">SubLink 2</a>
<a href="#">SubLink 3</a>
</div>
</div>
</div>
</div>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
There's no need for JS here - you can use the :focus-within
pseudo selector to trigger the sub-items when the parent is interacted with:
.columnb-sub:focus-within>.pages-links-sub
Note that I commented out the :hover
line here just so that the effect is noticeable. In reality you would use both to cover touch and non-touch devices.
.pages-links-sub div.dropdown-contentc {
display: none;
}
.columnb-sub>.pages-links-sub {
display: none;
}
/* .columnb-sub:hover > .pages-links-sub, */
.columnb-sub:focus-within>.pages-links-sub {
display: block;
div.dropdown-contentc {
display: block;
}
}
<div class="columnb">
<p class="pages-toptext">Standard Settings</p>
<div class="pages-links">
<a href="#">Link 1</a>
<div class="columnb-sub">
<a href="#">SubLinks 1 <i class="fa fa-caret-down"></i></a>
<div class="pages-links-sub">
<div class="dropdown-contentc">
<div class="columnb">
<a href="#">SubLink 1</a>
<a href="#">SubLink 2</a>
<a href="#">SubLink 3</a>
</div>
</div>
</div>
</div>
<div class="columnb-sub">
<a href="#">SubLinks 2 <i class="fa fa-caret-down"></i></a>
<div class="pages-links-sub">
<div class="dropdown-contentc">
<div class="columnb">
<a href="#">SubLink 1</a>
<a href="#">SubLink 2</a>
<a href="#">SubLink 3</a>
</div>
</div>
</div>
</div>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
As an aside to the issue, I would suggest using a <nav><ul><li>
structure for the menu as it's more semantic, and possibly better supported by accessibility tools.