skip to Main Content

I’ve been working on a coding project and I have been trying to have multiple "pages" in one html file (e.g. awsomesauce.com/page.html#videos and showing only the videos section) while having the same navbar and so far javascript has let me down. Any ideas?

<script>
// Get the current URL (awsomesauce.com/page#videos in this instance)
let url = window.location.href;
// Get the length of the current URL
let urlLength = window.location.href.length;
// Extract the portion of the URL starting from index 21
let  = url.substr(21, urlLength);
</script>

2

Answers


  1. If you have all the sections already on the page, you can hide/show your content with CSS, eg:

    <div class="section" id="A">A</div>
    <div class="section" id="B">B</div>
    <div class="section" id="C">C</div>
    

    For your CSS, use the :target pseudo-class to use the URL’s fragment (eg: #vidoes component) to apply the visibility style to:

    .section:not(:target) {
      display: none;
    }
    
    .section:target {
      display: block;
    }
    
    Login or Signup to reply.
  2. Please look at the URL interface and location.search which would be much more useful than the deprecated substr

    JS alternative to the better CSS solution posted here

    Code is assuming each "page" is a <section id="someID">...</section>

    const showID = location.search;
    if (showID) {
      document.querySelectorAll('section').forEach(section => section.hidden = !section.matches(showID));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search