-1

I am creating links to sections on the same page in HTML. By default they are not visible display : none. I want when my user clicks on the link (URL) which included id so it should set display : block. For example opening is the id when window.location.href includes #opening so content should be visible. User can simply hit mydomain#opening in the browser without clicking <a> or #id.

HTML

<p id="opening">Hyperlinks are utilized by a web browser to move from one page to another...</p>
<p>My Name is XYZ...</p>

CSS

#opening {display : none;}
Ujjawal Bhandari
  • 1,333
  • 1
  • 8
  • 16
  • Does this answer your question? [Show div #id on click with jQuery](https://stackoverflow.com/questions/12237163/show-div-id-on-click-with-jquery) – Don't Panic Apr 20 '21 at 07:27
  • No. User can simply hit mydomain#opening in the browser without clicking or #id. – Ujjawal Bhandari Apr 20 '21 at 07:34
  • It can be hard to come up with the right search terms, but please do try searching before posting a new question. There are *many* examples here on SO showing many variations on what you want to do, eg https://stackoverflow.com/questions/1822598/getting-url-hash-location-and-using-it-in-jquery, https://stackoverflow.com/questions/680785/on-window-location-hash-change – Don't Panic Apr 20 '21 at 07:39

1 Answers1

2

Try this :-

<a href="#opening" onclick="$('#opening').css({display: 'block'})" >Take me to the opening paragraph.</a>

OR

$("a").click(function() { 
   var href =  $(this).attr("href"); 
   href = href.replace("#",""); 
   $("#"+href).css("display","block"); 
})

On window load :-

$(document).ready(function() {
 var hash = window.location.hash.substr(1);
 if (hash) {
  $("#"+hash).css("display","block"); 
  }
});
Toxy
  • 696
  • 5
  • 9