I have a site example.com. When I visit this page example.com/#login I want to call a js alert function. How can I do this?
4 Answers
If you want a good cross-browser library for dealing with url's, I'd look into History.js
https://github.com/browserstate/History.js/
History.Adapter.bind(window,'statechange',function(){
// Note: We are using statechange instead of popstate
var State = History.getState();
// Note: We are using History.getState() instead of event.state
History.log(State.data, State.title, State.url);
});
And there's also Backbone.js, which may be way more than you need because it's an MV* framework, however it has a concept of a Router which is also helpful.
Comments
You can check the URL for #login. If it's present call the function. http://www.webmasterworld.com/forum91/216.htm
I recommend jQuery, and this approach: http://jquery-howto.blogspot.co.uk/2009/09/get-url-parameters-values-with-jquery.html
Comments
I think you can check if window.location.hash isn't a falsy value to check if there is a hash in the URL.
For example:
function someAlert(message) {
// This would be your alert function. This is just for example
alert(message);
}
// The "if the URL has a hash":
if (window.location.hash) {
someAlert("Hello URL with a hash visitor!"); // "Hello URL with a hash visitor!" can be whatever you want
}
If you want to save the whatever is after and including the hash, just use:
var hash = window.location.hash; // hash would be "#login" if the URL was http://example.com/#login