0

This is different from existing queries here.

I am facing removing #url when destination id is in different page.

Here's what I've done : There are 2 HTML pages : index.html & about.html. I have shown various Menu information using <div id="one"></div> in index.html page rather than separate page for every menu item, to remove #url when clicked I have tried the below lines separately.

history.pushState('', document.title, window.location.pathname);

var target = $(this.target);

However, #url is not showing only in index.html page. But, when clicked on menu items in about.html page the #url is still visible (because the <div id=""></div> are in index.html). Can you help me to remove #url even the destination id is in different page.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • Can you please define the URL in which you getting hash value? – Hitesh Kumar Sep 04 '20 at 07:44
  • 1
    The `history.pushState()` does remove the hash when I try it out. What is `this.target`? – Emiel Zuurbier Sep 04 '20 at 07:44
  • Look at https://stackoverflow.com/questions/13266746/scroll-jump-to-id-without-jquery / https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView – G-Cyrillus Sep 04 '20 at 07:53
  • this one seems to validate your requirement . (its all around event.preventDefault() to avoid click be efficient but fire only the script) https://stackoverflow.com/questions/28678548/trouble-with-an-one-page-navigation-updating-highlighting-active-state-and-scr – G-Cyrillus Sep 04 '20 at 08:13
  • Hi @HiteshKumar, I'm seeing #url when I click on Menu items { Destination content is in index.html } in about.html – Bezawada Harikrishna Sep 04 '20 at 08:54
  • Hi @G-Cyrillus , every strategy in the provided link working only for single page #url, But, for different page # they're not working. – Bezawada Harikrishna Sep 04 '20 at 09:03
  • Hi @EmielZuurbier, your are indeed only for same page #url. But, for different one it is still needs improvements. And this.target takes click as operation and moves to target directly. – Bezawada Harikrishna Sep 04 '20 at 09:06
  • i misunderstood the question :) – G-Cyrillus Sep 04 '20 at 09:34

1 Answers1

1

If I understand correctly you have two pages with identical navigation that include anchors with hash values, like: #target. But you don't have the elements that the anchors refer to at both pages, so the hash has no use on the page without the, for example: <div id="target">.

If that is the case then the snippet below could help. It reads the hash value from the location object and then tries to select the element with that hash. If no element is found on the page, the URL will be updated. Place this script on every page and run it instantly.

var hash = location.hash;
var $targets = $(hash);
if (!$target.length) {
  history.pushState('', document.title, location.pathname);
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32