Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  163] [ 6]  / answers: 1 / hits: 18840  / 13 Years ago, tue, october 18, 2011, 12:00:00

Possible Duplicate:

Handle URL anchor change event in js






Is it possible to have a javascript function run via an anchor tag.



E.g. if you went to... www.site.com/index.html#function1 ... Then function1 would run?


More From » anchor

 Answers
56

Put a an onload listener on the page and a click listener on the link that goes to the anchor. When fired, check window.location.href, something like:



<body onload=checkHash();>

<a href=#foo onclick=checkHash()>go to foo</a>
<br>
<a href=#bar>go to bar</a>

<p>something in between</p>

<a name=foo>foo</a>
<br>
<a name=bar>bar</a>

<script type=text/javascript>
function checkHash() {
// Check URL using setTimeout as it may not change before
// listener is called
window.setTimeout(doHashCheck, 10)
}
var doHashCheck = (function(global) {
return function() {
var fnName = window.location.hash.replace(/^#/,'');
console.log(fnName);
// fnName should be a native function, not a host method
if (typeof global[fnName] == 'function') {
global[fnName]();
}
}
})(this);

function foo() {
alert('foo');
}

if (!window.console) window.console = {};
if (!console.log) console.log = window.alert;
</script>
</body>

[#89544] Monday, October 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dallasb

Total Points: 657
Total Questions: 98
Total Answers: 97

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;