0

Example:

http://localhost/#view=1

If I want to get that variable "view", I need to get window.location.href, and then split the # and do something more.

This is my question:

<a href="#view=1">View 1</a>
<a href="#view=2">View 2</a>

Is there anyway to detect when View 1 click or view 2 click? For people click on View 2, a function will do for view=2.

OR I must do something like this:

<a href="#view=1" onclick="setview(1);">View 1</a>
<a href="#view=2" onclick="setview(2);">View 2</a>

I want when people copy the link http://localhost/#view=2 and send to there friend, the function setview(2) will be run when their friend visit the URL, and they don't need to click the link.

3
  • window.location.hash can give you that directly. You shouldn't have to split your URL. Commented Nov 10, 2012 at 17:22
  • 1
    You want the onHashChange event. Commented Nov 10, 2012 at 17:24
  • Is there anyway to know onhashchange without use other plugin? Commented Nov 10, 2012 at 19:38

1 Answer 1

4

You can use hashChange event

$(function(){
  // Bind the event.
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    alert( location.hash );
  })

  // Trigger the event (useful on page load).
  $(window).hashchange();
});

And now in the $(window).hashchange(); function, put your code:

$(window).hashchange(function(){
  $(location.hash).show();
});

In your case, it would be:

$(window).hashchange(function(){
  setview(location.hash[strlen(location.hash)-1]); // Get the last character, if this doesn't work.
});

Forgot to add the plugin: http://benalman.com/projects/jquery-hashchange-plugin/, which you would need to use.

Sign up to request clarification or add additional context in comments.

4 Comments

there is no shortcut .hashchange() method in jQuery API...need to use on()
I gave the definition for using hashchange with jQuery. It is here: benalman.com/projects/jquery-hashchange-plugin
OK...but that is using a plugin that was not referenced in your solution. Can simply use on() for what you are providing without a plugin
@Ken: $(window).on('hashchange', function(){ /* do stuff */ }); Also: check out the API reference for on().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.