0

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 4

5
// example.com/#login
if (window.location.hash) {
    alert("URL has hash");
    var hash = window.location.hash; // = "#login"
    callMyFunction();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

http://backbonejs.org/#Router

Comments

0

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.