How to call a js function when url contains anchor - javascript

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?

// example.com/#login
if (window.location.hash) {
alert("URL has hash");
var hash = window.location.hash; // = "#login"
callMyFunction();
}

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

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

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

Related

Javascript/jQuery hash URL doesn't execute

I have a hash URL that doesn't execute the javascript/jQuery unless I manually hit the enter key or refresh the page.
$(function($){
var key=$(location).attr('hash');
if (key){
$('#div').find('div.div2').load('sig.php?k='+key)
}
});
This works fine when I type in the URL manually or refresh the page but whenever I use <a href="url#SecReTkEy"> or Javascript/jQuery functions such as:
$(location).attr('href','url#SecReTkEy');
$('a').prop('href','url#SecReTkEy');
window.location.replace('url#SecReTkEy');
window.location.href('url#SecReTkEy');
Can any one tell me why and how to fix this?
`
you should use
location.href = #whatever
You don't need JQuery in order to retrieve the hash. Use the fully qualified reference to window.location.hash (I'm guessing location didn't work as you already have a var named location).
Also, don't forget to URL encode the key using encodeURIComponent. Additionally the $ is not needed if you want to execute this on document ready.
$(function(){
var key = window.location.hash;
if (key){
$('#div').find('div.div2').load('sig.php?k=' + encodeURIComponent(key))
}
});
I have a hash URL that doesn't execute the javascript/jQuery unless I manually hit the enter key or refresh the page.
This was due to it only launching once rather than having an eventBinder on hashchange.

Javascript page refresh to base URL, stripping query string, on browser resize -

I'm using this piece of javascript code to refresh the browser when the user resizes it:
<script type="text/javascript">
$(window).bind('resize', function(e)
{
if (window.RT) clearTimeout(window.RT);
window.RT = setTimeout(function()
{
this.location.reload(true); /* false to get page from cache */
}, 200);
});
</script>
It works fine, except - the page I'm using has a query string with certain values, like:
http://www.example.com/index.php?w=123&h=456
What I'd like is the same functionality but to have the page refresh to the URL without the query string (or at least without its values).
Is that possible?
since location is an object ,you can change the property 'href' to whatever you like , for example you can change the new location and assign it to the href property:
your current location is : http://www.example.com/index.php?w=123&h=456
when you need to refresh the page without the query string, you can do this: window.location.href = "http://www.example.com/index.php"
hope helps,
good luck
Try using window.location = window.location.pathname instead.
If you to redirect the page to root domain, then use window.location.origin. If you want to include the script name too then use window.location.origin and window.location.pathname. So your redirect can be replace with
window.location = window.location.origin + window.location.pathname

Change Hash without updating history stack

Is it possible to alter the hash of a page without calling the hashchange event?
As in my app I want to do something like:
$(window).hashchange( function(){
hash = ...; // here I change the hash to something else
window.location.hash = hash; // then update it
});
The obvious problem with the code above is that it will cause a loop as window.location.hash will call the hashchange event and then so and so on.
However in my app I only change the hash on a condition:
$(window).hashchange( function(){
var hash = window.location.hash;
var lastChar = hash.substr(-1);
if(lastChar != '/') {
// Add trailing slash
hash = hash.replace(/\/?$/, '/');
// Update the hash
window.location.hash = hash;
}
});
So that it only gets called IF a trailing slash isn't found, and then once it's added it then it won't enter the conditional again so it won't do the loop issue mentioned above.
BUT it will still call the hashchange event! And two problems arise from this:
The History is broken as the previous page is the current page and the browser gets stuck in an infinite stack of the current page.
I do an AJAX request in my app on hashchange so it will do the call twice just to add the trailing slash.
Is it possible to add that slash to the hash without it calling the event?
Perhaps doing window.unbind('hashchange'). Would that work? And also needs to work in HTML4 browsers so the HTML5 History API isn't an option here.
In HTML5 browsers you can use window.history.replaceState() to update the hash without causing a new history entry to be created.
According to the MDN docs, neither .pushState() or .replaceState() will trigger a hashchange event.
Doing this seems to work:
// Unbind hashchange
$(window).unbind( 'hashchange');
// Update the hash
window.location.hash = hash;
// Rebind hashchange
$(window).bind( 'hashchange');
Any thoughts on this? Such as unknown problems I may have etc.

How do I return part of the url using window.location.hash

I am really stuck
I am currently using the code below to add the name of a dynamically loaded page to the url
var value = $(this).attr('href');
e.preventDefault();
window.location.hash = value;
it almost works as its returning this in the url
http://www.sitename.com/dev888/#http://www.sitename.com/dev888/page-name
But I the only want part of the url to return like the example below
http://www.sitename.com/dev888/#/page-name
How can I edit the code above to get my desired result?
Thank!!
You can play with the value to get the last one like this
var value = $(this).attr('href');
e.preventDefault();
var parts = value.split("/");
value = parts[parts.length-1];
window.location.hash = value;
Or you can change the attr('href') to the value you want directly :)
I hope this can help
And you may want to take a look at pusState
https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history
The browser already does this for you. Just make your link's href the hash, and let the user click it normally:
Click!
It will automatically append #my-hash to the URL.
Trying to accomplish this with JavaScript is totally wrong, unless you require logic to prevent the click under certain conditions, and even then the correct behaviour is to specify your hash as the href of the link, conditionally allowing the click event to be handled by the browser.
Maybe you find interesting to obtain the title of the page and use it in the hash
var current_title = $(document).attr('title');
e.preventDefault();
window.location.hash = current_title ;

Javascript: Need to detect when a user revisits the page with a changed hash tag

Problem is (at least with my current browser), changing the hash tag and entering the new url doesn't trigger a refresh of the page, and thus I'm not aware offhand how to detect when this hash tag change has been made.
Is there an elegant way to do this?
Check for a new location.hash
This is a nasty-ish solution, but you can poll the URL for a change every so often:
var hash = window.location.hash;
function poll() {
if (window.location.hash != hash) {
hash = window.location.hash;
// Hash has changed. Do stuff here.
}
}
setInterval(poll, 100);

Categories

Resources