if function with window.location.hash help - javascript

I have a function that changes the hash in the url and inserts/removes a div from my main page. I did this was so that I can have a page that you can maneuver through without a reload, but at the same time i wanted people to be able to bookmark a certain section and go to it later without having to go through the page again.
When i try to call my hash() function, which closes all divs and opens up the specific div depending on the hash, it doesn't work. I probably dont have the right thing in the if statements, because when I put an alert() in the hash() function, it pops up like its supposed to.
function hash(){
if ( window.location.hash == "dcontact" ) {
removedivs();
InsertContent('dcontact');
}
if ( window.location.hash == "dhome" ) {
removedivs();
InsertContent('dhome');
}
}
hash();
I'm aware that there are probably better ways of doing everything i mentioned, but this is the only website I'm going to be making, and I couldn't care less how messy the script is in the end, as long as it works.

the reason it doesn't work is the actual hash (in the US I think you call it a pound) symbol - # at the beginning of window.location.hash
From memory IE doesn't put the hash symbol on it, so do this:
function hash() {
var hash = window.location.hash.replace('#','');
if (hash == "dcontact"){removedivs(); InsertContent('dcontact');}
if (hash == "dhome"){removedivs(); InsertContent('dhome');}
}
You could also consider just calling InsertContent(hash) rather than doing an if() for every different link you'll have

Related

Execute Javascript on Refresh Without the "Are you sure you want to leave the page" Prompt

In a certain case, I need to execute a few lines when the user refreshes the page.
Currently I do this with the onbeforeunload event as shown below, but I am looking for a way to do this without the prompt. I just want it to happen behind the scenes
The solution can be pure JS (preferred) or could be jQuery based.
//to kill the modal incase refresh or page exit
window.onbeforeunload = closingCode;
function closingCode() {
//bunch of functions here to run before refresh/close
window.location.href = window.location.href.split('#')[0]; //remove leftover hash symbol if it exists
return false;
}
Try this ;)
window.onbeforeunload = function(){
inst.close();
inst.destroy();
window.location.href = window.location.href.split('#')[0]; //remove leftover hash symbol if it exists
return;
}

Check if window.history.go successful?

Is there anyway to check if a window.history.go command is successful in changing the window.location or not?
i.e. If I do a window.history.go(-5) when there are only 3 pages in the history stack, the browser will do nothing.
Is there a way to check if that happens and run other code? An error callback, of sorts.
Thanks.
For an immediate response, first you'll want to check history.length to make sure it is at least 6, e.g. to go -5. Apart from that, I think the only way is to use setTimeout and if the script is still running, the callback will be executed.
Not really a JS expert, but if you want to perform some action when the user goes back or forward, you could use URL hashes and trigger some function using the jQuery onhashchange event. This will not give you the position in history, and i'm also not sure about cross-browser compatibility, but it did the job for me so far.
$(window).on('load' function(){
var hash = parent.top.location.hash;
if(hash == '' || hash == '#' || hash == null){
//if none, set a hash and reload page
parent.top.location.hash = '#/some/hash';
parent.top.location.reload(true);//use true if you dont want to use cached items
}
});
$(window).on('hashchange', function(){
do_something(parent.top.location.hash);
});
function do_something(hash){
//this function will be executed each time the '#' changes
console.log('hash changed to '+hash);
}

Javascript: Creating a 'weird' conditional re-direct

If I had a normal website this would be a simple enough fix... but I've built my site on tumblr so I need a workaround. Every page runs off of the same code, so any solution script is going to run on every page.. can't quite figure this one out (did I mention I'm a total n00b?). There are lots of answers to questions LIKE this one, but I couldn't quite find the right syntax I suppose to answer this question...
The goal here is, if some goes to just the raw domain name, in this case milliondollarextreme.tv --> I'd like it to redirect to milliondollarextreme.tv/tagged/videos.
In any other case, by that I mean, if there is anything appended to the end of the domain name already, such as:
milliondollarextreme.tv/permalink/91298132843
milliondollarextreme.tv/tagged/blog
milliondollarextreme.tv/contact.htm
I don't want there to be any redirection going on. I only want the redirect to 'fire' really the first time the person types in the domain -- milliondollarextreme.tv
The trick here, the reason why I am asking (I did a search and 1000 apologies if this has been asked elsewhere, I just couldn't find it) is that the script has to run on every page, because it's hosted on tumblr, so every page is driven by the same code.
Any ideas? Thanks in advance.
This will simply redirect any visit to milliondollarextreme.tv/ to milliondollarextreme.tv/tagged/videos
if(window.location.pathname == '/')
{
window.location.pathname = '/tagged/videos';
}
However, it will do it every time they go to the root; like Gerardo, I'm not clear if that's what you want.
<script>
if( window.location.href == "http://milliondollarextreme.tv" ||
window.location.href == "http://milliondollarextreme.tv/" ||
window.location.href == "http://www.milliondollarextreme.tv" ||
window.location.href == "http://www.milliondollarextreme.tv/") {
window.location.href = "http://www.milliondollarextreme.tv/tagged/videos/";
}
</script>
What should happen when someone enters to http://milliondollarextreme.tv/ for the second time?

Can you use hash navigation without affecting history?

I'm afraid it might be impossible but is there a way to change the hash value of a URL without leaving an entry in the browser's history and without reloading? Or do the equivalent?
As far as specifics go, I was developing some basic hash navigation along the lines of:
//hash nav -- works with js-tabs
var getHash = window.location.hash;
var hashPref = "tab-";
function useHash(newHash) {
//set js-tab according to hash
newHash = newHash.replace('#'+hashPref, '');
$("#tabs li a[href='"+ newHash +"']").click();
}
function setHash(newHash) {
//set hash according to js-tab
window.location.hash = hashPref + newHash;
//THIS IS WHERE I would like to REPLACE the location.hash
//without a history entry
}
// ... a lot of irrelavent tabs js and then....
//make tabs work
$("#tabs.js-tabs a").live("click", function() {
var showMe = $(this).attr("href");
$(showMe).show();
setHash(showMe);
return false;
});
//hash nav on ready .. if hash exists, execute
if ( getHash ){
useHash(getHash);
}
Using jQuery, obviously. The idea is that in this specific instance 1) making the user go back over every tab change could effectively 'break the back button' by piling up needless references, and 2) not retaining which tab they're currently on if they hit refresh is an annoyance.
location.replace("#hash_value_here"); worked fine for me until I found that it doesn't work on IOS Chrome. In which case, use:
history.replaceState(undefined, undefined, "#hash_value")
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.
Remember to keep the # or the last part of the url will be altered.
location.replace("#hash_value_here");
The above seems to do what you're after.
Edit: It's been a couple years now, and browsers have evolved.
#Luxiyalu's answer is the way to go
--Old Answer--
I too think it is impossible (at this time). But why do you need to change the hash value if you are not going to use it?
I believe the main reason why we use the hash value as programmers is to let the user bookmark our pages, or to save a state in the browser history. If you don't want to do any of this, then just save the state in a variable, and work from there.
I think that the reason to use a hash is to work with a value that is out of our control. If you don't need it, then it probably means you have everything under your control, so just store the state in a variable and work with it. (I like repeating myself)
I hope this helps you out. Maybe there's an easier solution to your problem.
UPDATE:
How about this:
Setup a first hash, and make sure it gets saved in the browser history.
When a new tab gets selected, do window.history.back(1), that will make the history go back from your first init hash.
Now you set the new hash, therefore the tabbing will only make one entry in the history.
You'll probably have to use some flags, to know if the current entry can be "deleted" by going back, or if you just skip the first step.
And to make sure, that your loading method for the "hash" doesn't execute, when you force the history.back.
You can always create an event listener to catch click events on the hyperlink and in the callback function put e.preventDefault(), that should prevent the browser from inserting it into the history.

Page history - back button exists?

Is it possible check if there is a value for history.go(-1)? I know you can't access history.previous directly.
I am trying to stay away from document.referrer because I know it can be blocked in some instances.
Here is what I am trying to do. I have an error page, on this page I would like to either have a BACK button (if it's not the only item in history) or a close button (if it is).
if (history.length) {
//There is history to go back to
history.go(-1);
}
Actually, history.length is always one or more, since the current page counts. Also, if you have a forward history (i.e. you used the back button), those pages also count. So you need a more complicated check:
if( (1 < history.length) && document.referrer ) {
There is no cross-browser approach to accomplish this. Document.Referrer may be set even if no history entry exists.
I came up with the following "hack". It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.
window.goBack = function goBack(fallback){
var useFallback = true;
window.onbeforeunload = function(){
useFallback = false;
}
window.history.back();
setTimeout(function(){
if (useFallback){ window.location.href = fallback; }
}, 100);
}
You can call this function using goBack("fallback.example.org").
One of the use cases is that you may want to add a back button to any page and also want to make sure that this back button works even if the user goes directly to this page (e.g. by bookmark, direct link etc).
So either it does perform a history.back() or if there is no entry, it'll redirect to a fallback.
If the history has a length greater than 0, then it contains at least one history point.
if (history.length)
function test() {
document.URL = document.referrer;
}

Categories

Resources