2

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?

Community
  • 1
  • 1
Philip Kirkbride
  • 17,347
  • 30
  • 101
  • 195
  • As mentioned below, write a function in document.ready() that checks the location.hash to get the value and perform the action required. – Zachary Oct 18 '11 at 23:02

4 Answers4

2

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

Justin Lucas
  • 2,256
  • 14
  • 22
2
    $(document).ready(function() {

        //Get hash from URL. Ex. index.html#Chapter1
        var hash = location.hash;

        if (hash == '#Chapter1') {
            //Do stuff here
        }
    });
Randy Burden
  • 2,331
  • 20
  • 31
  • 1
    Is the *ready* function called when following an anchor (i.e. navigation in the page) or only when following a URL (i.e. navigation to another page)? – RobG Oct 18 '11 at 23:21
  • 1
    @RobG This would fire on page load and not when navigating from within the page. So if someone landed on the page with the anchor tag in the url, this would fire. – Randy Burden Oct 21 '11 at 19:31
2

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>
RobG
  • 124,520
  • 28
  • 153
  • 188
  • 1
    Should have explained that *setTimeout* is needed in Firefox (and maybe others) as the listener is called before the URL is modified. – RobG Oct 18 '11 at 23:48
0

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.

Matt H
  • 6,195
  • 2
  • 23
  • 31