Skip to content Skip to sidebar Skip to footer

Could A Page Display Diferrent Content If The Url Hash Changes?

How could a page display different content based on the URL hash? I'm not talking about the browser scrolling down to display the anchored section, but something like JavaScript re

Solution 1:

Oh yes - it's becoming a common pattern to handle page-state-to-URL persistence when content is AJAX driven.

Javascript can access this value via window.location.hash. Once that's done, you can perform any actions based on the value of that hash

  • Show/hide nodes
  • Makes other AJAX calls
  • Change page titles or colors
  • Swap images
  • etc

Really, any DHTML effect.

Solution 2:

This is occasionally done. Youtube uses hashes to link to specific timestamps within a video.

EDIT: I had assumed that you might have an issue where if the user goes up and manually edits the hash in the address bar, the page doesn't reload and even javascript will not know that it changed. I was wrong. I tried it on Youtube it works.

Solution 3:

I just built a system to do this a few weeks ago

depeding on the browser you need to detect the hash, heres how to do that

// test all possible places hash could be on different browsers
if(window.location.hash){
   hash = window.location.hash;
} elseif (document.location.hash){
   hash = document.location.hash;
} elseif (location.hash){
   hash = location.hash;
}

// some browsers start the hashwith#, remove it for consistencyif(hash.substring(0,1) == '#'){
    hash = hash.substring(1,hash.length);
}

Then handle the value of the hash variable to trigger page changes as you please.

for example: http://www.example.com#pageA

if(hash = 'pageA'){
  document.getElementById('mainContentDiv').innerHTML = '<p> content for the page displayed when the hash sais pageA</p>';
}

Solution 4:

Sammy is a javascript library that does just this.

Solution 5:

As JavaScript has access to the URL-string it could of course act differently on the contents of the url.

I've occassionally seen something like this but I don't think that this is a good way to react unless in very specific uses.

One of the uses I remember was TiddlyWiki using the after-portion of the hash to set preferences for the page rendering and such.

Post a Comment for "Could A Page Display Diferrent Content If The Url Hash Changes?"