Home > Enterprise >  scroll to a target which is inside a hidden container
scroll to a target which is inside a hidden container

Time:09-06

Clicking a hash link (<a href="#content">Go to content</a>) jumps the document to the target container (<div id="content">Content here</div>). But when the target container is hidden (display: none;) it doesn't jump to it. I tried adding a click event listner to show the target container when the hash link is clicked, but still it doesn't jump to the target container.

How to fix that?

CodePudding user response:

when display: none; is added in HTML, the page will be displayed as if the element is not there. You can use visibility: hidden; which will still occupy the same space. To reduce the height you can use the height: 0; attribute.

<div id="a">
</div>
<div id="b">
</div>
<a href="#a">Go to content</a>
<a href="#b">Go to content</a>


#b {
  height: 500px;
  background-color: blue;
   }
#a {
  background-color: red;
  height: 0px;
  visibility: hidden;
  }

CodePudding user response:

The following snippet sets up an event listener for all clicks on <a> elements in the body of the document. If the href of the clicked link starts with # we have a "local link" and this will trigger a removal of the .hidden class from the targeted element.

document.body.addEventListener("click",ev=>{
 const trg=ev.target;
 if(trg.tagName==="A"){
  const href=trg.getAttribute("href");
  if (href.match(/^#/))
   document.querySelector(href).classList.remove("hidden");
 }
})
div { min-height: 300px; width: 90%; background-color: #eee; margin: 10px; padding: 10px}
div#content1 {background-color: #fdd;}
div#content2 {background-color: #dfd;}
.hidden {display:none}
<a href="#content1">Go to content "one"</a><br>
<a href="#content2">Go to content "two"</a>
<div>The above link jumps within the document to the target container.</div><div id="content1" >Content "one" here.</div>
<div>Another div to fill the page</div>
<div>One more div ...</div><div id="content2" >Content "two" here.</div>
<div>... and her the final one.</div>

  • Related