CSS: freeze /: focus versus click on event (mobile) touch devices

Often I find myself in situations where I need to display a menu on hover, and the menu of mobile devices should open by clicking. Now, for example, consider the following example:

.btn { width: 200px; background-color: #333; color: white; padding: 10px; } .menu { display: none; padding: 15px; } .btn:hover .menu { display: block; } .btn:focus .menu { display: block; } 
 <div class="btn"> Button <div class="menu">I am menu</div> </div> 

Now it automatically works on mobile devices, because the hang state on touch devices is sticky. But is this hack applicable to all touch devices? That is, is the risk worth it? Will some touch device not freeze? Obviously, an alternative is to set touch / click events using JavaScript on touch devices, but this seems redundant because I haven't seen any touch devices that don't have sticky hover states?

So my question is:

Is it possible to use a hacked state of chaos or use JavaScript events to make it more bulletproof?

+6
source share
2 answers

I would say that everything is in order to just stick to css for most hangs if you are ok with the menu or closing when the user clicks on a single item.

I do not know about mobile browsers that do not adhere to this behavior, at least that are not the main ones. If any of the main browsers have omitted this, you will need to rebuild a huge piece of the mobile network.

Probably safe!

+3
source

In my experience, this is actually not a hack, but rather a way to simulate hover events using pure CSS. I mainly use :hover/:focus for such problems, because

1.) They are reliable.

2.) Cheap (in terms of kb).

To enable a rule for a fully functioning menu, you need only 2 rules and an external HTTP request, but a few lines of JavaScript (or, horror, jQuery) to create the same thing.

What I said in the comments, you should or could use the tabindex attribute to make the element be customizable, for example:

 <div class="non-focusable-clickable-hover-element" tabindex="-1">I cannot be focussed<div> <div class="focusable-hover-element" tabindex="1">I can be focussed<div> 
+2
source

Source: https://habr.com/ru/post/1013470/


All Articles