mscmdaddcts
mscmdaddcts

Reputation: 31

Add dynamic content with URL elements

I have a question and I wonder if it's possible. I want to add dynamically content into an html page, by changing the id in the URL.

I mean, for example I want to add the name of a person to a web page:

At first my page would be : www.mypage.com/index

<p> Hello <span></span> welcome to our page</p> 

The result I want to get, is by writing this url: www.mypage.com/index#YourName the code updates itself to this:

<p> Hello <span id="YourName">YourName</span> welcome to our page</p> 

So the id and the content of the span updates juste by modifying the URL. I don't really know how to achieve that. I wonder if I could give to my span dynamically an id by typing it on the url, and then retrieve this id and use it as a the value of the span.

Upvotes: 0

Views: 1014

Answers (3)

Alexandru Bulat
Alexandru Bulat

Reputation: 89

You can get the ID value from the url by using window.location.hash.

Additionally, you can watch these changes by using the hashchange window event.

function showHash() {
  const newHash = window.location.hash.replace("#", "");
  const resultSpan = document.querySelector(".hash-value");
  
  resultSpan.id = newHash;
  resultSpan.innerHTML = newHash;
}

window.addEventListener("hashchange", showHash, false);
window.addEventListener("DOMContentLoaded", showHash);
<body>

  <div>Current HASH in URL is: <span class="hash-value"></span></div>

  <div class="buttons">
    <a href="#hash1">hash1</a>
    <a href="#hash2">hash2</a>
    <a href="#hash3">hash3</a>
  </div>
</body>

Upvotes: 1

dm_tr
dm_tr

Reputation: 4783

Maybe you can try this

let splits = window.location.href.split("#");
let span = document.getElementsByTagName("p")[0].getElementsByTagName("span")[0];
span.innerText = splits[splits.length - 1];
span.id = splits[splits.length - 1];

Upvotes: 0

hayate
hayate

Reputation: 3

You can use JavaScript to get a current link such as:

<script>
   let YourLink = window.location.href;
   let startingPoint = YourLink.indexOf('#');
   let endingPoint = YourLink.indexOf('/'); // In case if the name is not the last thing on your link
   let NameYouWant = YourLink.substring(startingPoint, endingPoint);

   // So 'NameYouWant' would be the name you need to use
</script>

In case you use '#' for the starting point of every name in your link, hope it's helpful.

Upvotes: 0

Related Questions