Home > Software design >  Problem with pointer-events and a:focus in CSS
Problem with pointer-events and a:focus in CSS

Time:12-28

I have a problem with my navbar, can someone help me ?

I have different links (<a>) that "unfold" an unordered list (<ul> of links <li><a><li>).

My <ul> is set to opacity: 0, and in my CSS I have :

.tab ul {
  opacity: 0;
  pointer-events: none;
}

.tab a:focus   ul {
  opacity: 1;
  transform: translateY(0px);
  pointer-events: all;
}

(this is only the part of the code that doesn't work)

When I click the link, the tab does unfold, and pointer-events is set to all (I know it is because the sublinks color changes when hovered). My problem is that whenever I click a sublink, the focus on the tab link is lost, and it seems to set pointer-events to none BEFORE executing the sublink's action (a basic href="page.html").

I tried removing :focus (as if the tab was in constant focus state), and the sublinks redirect me on the pages as intended.

I also tried putting pointer-events: all on ul > li > a, but it didn't work.

That's why I came to the conclusion that the tab link lose focus and the pointer event is set to none before the sublink is actually clicked.

Does someone know a way to work around this and execute the sublink's action before the focus loss ?

The tab is unfold and the sublink is hovered (mouse invisible on the screenshot thought) :

The tab is unfold and the sublink is hovered (mouse invisible on the screenshot thought)

Here is the complete website, if needed (work in progress) : https://mm01.thorelnicolas.fr/a21/gonnetvi/projet/

CodePudding user response:

If I understood you correctly, then maybe add this solution can help you:

.tab a   ul:hover {
  opacity: 1;
  transform: translateY(0px);
  pointer-events: all !important;
}

Because the focus of the link is lost, the submenu disappears, but you can leave the submenu by ul:hover.

P.S. By the way, on the example of the site that you specified, add this code at the end, it quite works (I tried using Web Inspector):

.menu-loisirs a   ul:hover, .menu-sports a   ul:hover {
    opacity: 1;
    transform: translateY(0px);
    pointer-events: all !important;
}

CodePudding user response:

For this kind of interaction, :focus-within is usually quite suitable. When the "trigger" link and wrapper of its children share same wrapper, it makes sense to bind logic to state of that parent wrapper. To make such structure keyboard accessible, can use .wrapper:not(:hover):not(:focus-within) .trigger .content { /* visually hidden state styles */}:

.tab:not(:hover):not(:focus-within) a   ul {
  display: none; /* for brevity, use accessible hiding in real world */
}

/* not necessary */
p[id]:not(:target) {
  display: none;
}

a[href]:empty:before {
  content: '           
  • Related