Search code examples
javascripthtmlhashchange

Expand details element when URL is called with specific hashes


I have used the details and summary elements to collapse a section of a page.

<details id="comments">
  <summary>Show comments</summary>
  <ol>
   <li id-"comment-101">This</li>
   <li id-"comment-102">is</li>
   <li id-"comment-103">cool</li>
  </ol>
</details>

I have also added this Javascript code to automatically expand the section if the URL is called with the #comments hash:

function openTarget() {
  var hash = location.hash.substring(1);
  if(hash) var details = document.getElementById(hash);
  if(details && details.tagName.toLowerCase() === 'details') details.open = true;
}
window.addEventListener('hashchange', openTarget);
openTarget();

How can I also expand details#comments when the URL is called with any #comment-X hash using Javascript (no jQuery)? Ideally the page would also scroll to the point where the element #comment-X is present.


Solution

  • It's a question of relaxing your check of the hash to allow more than just exactly "comments", but also "comment-111". I have assumed, as your HTML suggests, that your IDs are numeric.

    //grab hash and its parts
    let hash = location.hash.match(/^#(comment(s|-(\d+)))$/);
    if (hash) {
    
        //resolve to element
        let el = document.getElementById(hash[1]);
        if (el) {
    
            //open comments - not sure what your .open property does
            el.closest('#comments').open = true;
    
            //if is hash to specific comment, go to it
            if (hash[3]) location.href = '#'+hash[3];
        }
    }