home

Javascript hash change

Javscript hash change event probably, used to change colors or pages by changing url, this event occurs when there has been changes after hash (begins with '#' symbol) of the current URL. An example what is default url is ustutorials.com/javascript-tutorials/javascript-hash-change.html# (by default it has yellow color-ffcc00). When you manually change the url yellow (ffcc00) to red (ff0000) the automatically window color change to red, to understand more have look into javascript hash change below example code.

window.addEventListener("load",function1);
function function1(event){
if(window.location.hash == ""){
  window.location.hash = "#ffcc00";
  }else{
  document.getElementById("container").style.backgroundColor = window.location.hash;
  }
window.addEventListener("hashchange",function1); document.getElementById("container").addEventListener("click",function2); }

function function1(event){ document.getElementById("container").style.backgroundColor = window.location.hash;
}
function function2(event){ window.location.hash = "ff0000"; }

By default url will be like this with yellow color window: ustutorials.com/javascript-tutorials/javascript-hash-change.html

After hash change (#ff0000) url will be like this with red color window: ustutorials.com/javascript-tutorials/javascript-hash-change.html#ff0000 Coming to the javascript hash change code, in the very first line we are loading window, along with function(function1), in side condition if hash null(window.location.hash == "") #ffcc00 will apply for particular div which has an id container. And most important things is after else we have condition (document.getElementById("container").style.backgroundColor = window.location.hash;) it means when user change the color in url after hash(#) that color will reflects to container div as well.

Also we have other event (click event), in this case when user responds to click on container div, that box color will change to red and also change url(#ff0000). To understand this please check below demo.

// to change box color enter some other color code in the url http://ustutorials.com/javascript-tutorials/javascript-hash-change.php#f0f