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?
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?
You can't do that by simply including it in the anchor tag but you could use the hashtag (location.hash
) in order to call your function
$(document).ready(function() {
//Get hash from URL. Ex. index.html#Chapter1
var hash = location.hash;
if (hash == '#Chapter1') {
//Do stuff here
}
});
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>
You can't call the javascript like that, but if you control the other site, you can check the URL in the body Load event, then execute a script.