Hash targeting

In this example below you will see how to do a Hash targeting with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by tappily, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright tappily ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Hash targeting</title>
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <label>
  text
  <input id='text' type='text'>
</label>
<label>
  <input id='radio' type='radio'>tab 1</input>
</label>
<label>
  <input id='check' type='checkbox'>toggle</input>
</label>
<button id='submit' type='submit'>submit</button>
<a id='anchor' name='anchor' tabindex='0'>anchor</a>
<video controls='' id='video' src='//ia700704.us.archive.org/6/items/1967MireilleMathieuMonCopainPierrot/1967_mireille_mathieu_mon_copain_pierrotScopitone_512kb.mp4' tabindex='0'></video>
<details id='details'>
  <summary>summary</summary>
  details
</details>
<dialog id='dialog'>
  details
  <form method='dialog'>
    <button type='submit'>submit</button>
  </form>
</dialog>
<nav>
  <a href='#text'>target text input</a>
  <a href='#radio'>target radio input</a>
  <a href='#check'>target check input</a>
  <a href='#submit'>target submit button</a>
  <a href='#anchor'>target anchor</a>
  <a href='#video'>target video</a>
  <a href='#details'>target details</a>
  <a href='#dialog'>target dialog</a>
</nav>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/tappily/hash-targeting-ZYVypB */
body {
  padding: 5em;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  min-height: 50vh;
}
button {
  padding: 1ex 1em;
  margin: 0 1em;
}
nav {
  padding: 1ex 0;
}
body :target,
body :focus {
  background-color: limegreen;
}


/*Downloaded from https://www.codeseek.co/tappily/hash-targeting-ZYVypB */
window.addEventListener('hashchange', hashHandler, false);
window.addEventListener('load', hashHandler, false);

function hashHandler() {
  var h = this.location.hash;
  if(!h) {
    return;
  }
  
  var e = this.document.querySelector(h);
  if(!e) {
    return;
  }
  
  if(typeof e.checked === 'boolean') {
    e.checked = true;
  }
  if(typeof e.open === 'boolean') {
    e.open = true;
  } else if(e.nodeName === 'DETAILS' || e.nodeName === 'DIALOG') { //help Safari and Polyfills
    e.setAttribute('open', '');
  }
  if(typeof e.play == 'function') {
    e.play();
  }
  if(typeof e.focus == 'function') {
    e.focus();
  }
  
  // TODO: videotracks (no support anywhere)
}

Comments