whats the issue with this header : header links referral to a different url?

Viewed 51

I am developing a single page application with several #sections

I have my header with my links in my nav which each refer to an #anchor (section) in this same page.

But I still have 2 pages like the legal notices and privacy policies apart.

My problem: in these 2 pages in question the links of the header.php which refer to #sections no longer work.

Would it be possible in JavaScript that depending on the page on which we find the header links not refer to #sections but to my index.php #section ??

I hope to be clear!

A big thank you in advance to whoever can help me !!

2 Answers

I'm not exactly sure the specific code you'd want, but could you do something like:

if(window.location.pathname == "page1"){

}else if(window.location.pathname == "page2"){

}

You can change the links on your page based on whether or the hash navigates to an ID on your page. You can grab each anchor tag (with a href property containing a # - this is done using the *= CSS selector) inside your navigation bar and loop over each link. For each link, you can grab the ID/hash, and check using querySelector() if an element with the provided id exists. If it doesn't, you can change the link of your current anchor tag to point to your index page, with the hash appended.

See example below (hover over anchor tags to see links)

document.querySelectorAll(".menu a[href*='#']").forEach(anchor => {
  const hash = anchor.getAttribute("href"); // grab hash
  if(!document.querySelector(hash)) { // check if element with hash ID exists
    anchor.href = "index.php" + hash; // change link if it does not exist
  }
});
body {
  margin: 0;
}

.menu {
  display: flex;
  position: fixed;
  flex-direction: row;
}

.menu a {
  margin-right: 5px;
}

.box {
  height: 100vh;
  width: 100vw;
}

#a {
  background-color: lime;
}

#b {
  background-color: red;
}
<nav class="menu">
  <a href="#a">Home</a> <!-- Remains -->
  <a href="#b">About</a> <!-- Remains -->
  <a href="#c">Contact</a> <!-- Changes -->
  <a href="https://www.google.com">Normal</a> <!-- Remains -->
</nav>
<section id="a" class="box"></section>
<section id="b" class="box"></section>

Related