Find the URL anchor, the part of the address after # in JavaScript
With JavaScript being responsible for rendering a lot of content on pages, it is often hard or impossible to link to specific content. I deal with this by reading the URL anchor, e.g. the part of the URL after the # character.
In this example, the URL anchor is ascertained, and if an element exists on the page with the same name, the 'onclick' event is fired for that object. Bear in mind this is only an example, you may want to do something else with the name, for example pass it to a function.
1. if(location.href.indexOf('#')>0)
2. {
3. var URL_anchor = location.href.substr(location.href.indexOf('#')+1);
4.
5. if(document.getElementById(URL_anchor)!=null)
6. {document.getElementById(URL_anchor).onclick();}
7. }
8.
9. // URL_anchor is also available after this code executes
Comments