Reputation: 5371
I know the title is too general. I couldn't find a specific title.
Here is the sample https://jsfiddle.net/Exlord/1soagsL5/
HTML
<ul>
<li>item1</li>
<li>item1</li>
<li>item with submenu >
<ul>
<li>item1</li>
<li>item1</li>
</ul>
</li>
<li>item1</li>
<li id='clickable'>item1</li>
</ul>
JavaScript
var el = document.getElementById('clickable');
el.addEventListener('click', function(e) {
console.log(e.target);
}, false);
CSS
ul {
list-style: none;
margin: 0;
padding: 0;
width: 200px;
max-width: 100%;
}
li {
background: gray;
padding: 5px;
border: solid 1px black;
position: relative;
}
li:hover > ul {
display: block;
}
@media all and (min-width: 481px) {
ul ul {
display: none;
position: absolute;
left: 100%;
top: 0;
}
}
@media all and (max-width: 480px) {
ul ul {
display: none;
}
}
Try it, it's a very simple menu, hover the middle item item with submenu, a simple submenu will be shown with simple CSS :hover
.
Click on the last item, it has a click event, it will fire correctly.
Now open this in Chrome's mobile device mod with touch simulation.
Click/touch the item with submenu, the submenu will open inside the parent element. This is the expected behavior.
Now click/touch the last element. The click event will not fire.
How can I fix this with CSS only hover
?
UPDATE : As far as I can tell the problem is that on first touch the last hovered element (li
with submenu) gets unhovered and the submenu ul
gets hidden and the parent ul
's height shrinks and the li
element that was under the touched point moves up, so its not under the touched point anymore and it does not get clicked/touched !!!!
Upvotes: 3
Views: 886
Reputation: 484
I think you figured out the cause on your own. The click target does seem to move away before event reaches the element.
The easiest solution I see is to use some supplementary Javascript to open and close the submenu on clicks. You use Javascript for the #clickable
event anyway so a little more won't be detrimental, just as long as you keep the :hover
for cases where Javascript is fails to load.
Original Answer
Touch devices do not have a hover state, due to the hardware interface. Browser makers chose a compromise to allow for sites which rely on it. Whenever a hover event/style is defined for an element the first tap will trigger that effect instead of the click. A second tap should, at least in most cases, trigger the original click event.
For your particular case you don't have a
ul
within theli#clickable
, but the:hover
is still detected and the browser behaves as it was designed. Excluding your#clickable
from the hover event will theoretically fix it (I am not able to test it myself at this time).li:not(#clickable):hover > ul { display: block; }
Upvotes: 0