3

Basically, I want to have links throughout the page that change the anchor -- the part of the URL after a # symbol. When that part of the URL changes, the JavaScript should respond.

I could add an onclick method to every link, but is there a better way?

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70

7 Answers7

4

That's not an anchor, it's the hash?

$(window).on('hashchange', function() {
    alert('My fracking hash changed to : '+document.location.hash);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Ugh, onhashchange. Thanks, I was looking for something like onanchorchange. I thought the text after the hash was called the anchor. Thanks. – Ken Kinder Sep 06 '12 at 16:20
  • Nope, it's the hash, and yes, it's the `onhashchange` event that is triggered everytime it changes. And it's available for setting/getting in the `document.location.hash`. – adeneo Sep 06 '12 at 16:22
4
$(window).bind('hashchange', function() {
  // code here
});

think that should do it

joevallender
  • 4,293
  • 3
  • 27
  • 35
1

In jQuery you don't need to add onclick events to all links individual. With a selector like $('a') you could add an event to all of your links at once.

$('a').click(function(){
    // code here
});

Inside this event you can use the $(this) object to get the href.

But I suggest that the other answers show you a more elegant way for solving this problem.

danijar
  • 32,406
  • 45
  • 166
  • 297
0

First of all you have to pick the element.

For example var links = $("a");

Then you add the jquery function .click()

andres83
  • 310
  • 1
  • 12
0

you can add a delegate to a,

$(elements).on(events, selector, data, handler);

the difference is it won't add "onClick" to every a element, but it will catch the "onClick" event of a

fengd
  • 7,551
  • 3
  • 41
  • 44
0

Try this

  1. Store window.location.hash on a global variable, say, currentHash
  2. Create a function to check window.location.hash !== currentHash
  3. If the check fails set currentHash = window.location.hash
  4. Execute this function using setInterval on DOMReady
naveen
  • 53,448
  • 46
  • 161
  • 251
0

Sammy.js is your friend here. I've used it on a SPA I'm working on and I love it!

Simon
  • 2,810
  • 2
  • 18
  • 23