open link inside a ‘details’ element

‘Details’ html tag is a very easy way to collapse/expand a web content: you can see it in the following example. This is the code:

<details>
<summary>expansible title</summary>
<p>all the content you want: text, images, video, in a nutshell: all possible content</p>
</details>

and this is the result:

expansible title

all the content you want: text, images, video, in a nutshell: all possible content

But there is a problem: the collapsed content is not reachable unless you click over his ‘summary’ (in the example above: ‘expansible title’) . Therefore a link from outside the details content toward some element inside that, doesn’t work, because it cannot open it.

To fix this problem you can use a little javascript:

  const openDetailsIfAnchorHidden = evt => {
  const targetDIV = document.querySelector(evt.target.getAttribute("href"));
  if ( !! targetDIV.offsetHeight || targetDIV.getClientRects().length ) return;
  targetDIV.closest("details").open = true;
 }

 [...document.querySelectorAll("[href^='#']")].forEach( 
   el => el.addEventListener("click", openDetailsIfAnchorHidden )
 );

to be put at the bottom of a page (otherwise it doesn’t work).

Lascia un commento

Il tuo indirizzo email non sarĂ  pubblicato. I campi obbligatori sono contrassegnati *