onHashChange running onLoad... awkward - javascript

So I'd like my page to load content if a window's hash has changed.
Using Mootools, this is pretty easy:
$extend(Element.NativeEvents, {
hashchange: 1
});
and then:
window.addEvent('hashchange', function() {});
However, the hashchange event is firing when the page is being loaded, even though the specification require it not to fire until the page load is complete!
Unless I am loading the page for the first time, with no hash, then all works as expected.
I think the problem here is the fact that the browser considers the page load "complete", and then runs the rest of the JavaScript, which includes hash detection to load the requisite page.
For example, if I typed in http://foo.bar/, all would work fine. However, http://foo.bar/#test would, ideally, load the initial page, detect the hash, and load the "test" content.
Unfortunately, the browser loads the initial page, considers it "domready", and THEN loads the "test" content, which would then fire onHashChange. Oops?
This causes an infinite loop, unless I specifically ask the browser NOT to update the hash if an onHashChange event is firing. That's easy:
var noHashChange;
noHashChange = true;
var hashes = window.location.hash.substr(1).split("/"); // Deciphers the hash, in this case, hashes[0] is "test"
selectContent(hashes[0]); // Here, selectContent would read noHashChange, and wouldn't update the hash
noHashChange = false;
So now, updating the hash AFTER the page has loaded will work properly. Except it still goes nuts on an initial page load and fetches the content about 3 or 4 times, because it keeps detecting the hash has changed. Messy.
I think it may have something to do with how I am setting the hash, but I can't think of a better way to do so except:
window.location.hash = foobar;
... inside of a function that is run whenever new content is selected.
Therein lies the problem, yes? The page is loaded, THEN the content is loaded (if there is content)...
I hope I've been coherent...

Perhaps you could check the hash first to eliminate the recursion:
if(window.location.hash != foobar){ window.location.hash = foobar;}
Why is the onHashChange handler changing the hash anyways? If there's some default that it's selecting first before loading the content, then perhaps that could go in a seperate function.
(I say this because it looks like you've some sort of directory structure-esque convention to your location.hash'es, perhaps you're selecting a specific leaf of a tree when the root is selected or something?)

you could implement an observer for the hash object that will trigger a function when the has object has changed.it does nothing to do with the actual loading of the page.
the best way to do this is via Object.prototype.watch
see other pages on same topic : On - window.location.hash - Change?

have a look at MooTools History it implements the onhashchange if the new html5 history api isn't available, no need to reinvent the wheel :)

Related

jquery fail on DOM modify made with html()

In my website, I build the page navigation based on hashchange:
var hashHome;
$(window).bind( 'hashchange', function(e) {
var homeClass = "home";
var url = $.param.fragment();
if($('#page-content').hasClass(homeClass)){
hashHome = $('#page-content').html();
}
if(url ==''){
//homepage with nothing(no hash)
if(!$('#page-content').hasClass(homeClass)){
//alert("load frim cache ->#"+url);
$('#page-content').addClass(homeClass);
$('#page-content').html(hashHome);
}
}else{
//go to some page
if($('#page-content').hasClass(homeClass))
$('#page-content').removeClass(homeClass);
initAction(url);
}
})
$(window).trigger( 'hashchange' );
When the site loads its homepage, the homepage gets stored in hashHome. If user navigates away, the initAction(id) replaces the entire $('#page-content')'s content with other pages' content. When the uses navigates back to home, it restores the stored home back to the $('#page-content').
My problem is that all of the jQuery stopped working on the homepage.
I've read about live() already but it seems that it needs a event like click() for it to work. How do I fix this?
I figured out that i need to store my entire page before i change the content of the div that is surrounding it
var content$('#page-content').html();
then do the content change
that way, when i reinitialize all my jQuery plugins, they will loose all of their old reference and use the new content variable, instead of a double initialization
and finally, i've the original question's code also won't work since the script tag look like this: <script type="text/javascript">...</script>, IE for some reasons won't recognize this, so I have to change it to <script></script> in order to make it cross browser compatible

passing different variables to same page

I am trying to build a web app mainly using html and javascript. I use a number of different variables in the app that are passed through the url.
here are the problems, I have some links that link to the page the app is currently on, just with changed variables, but while clicking on the links does change the url value, the page does not change/reload for the new values when using and an href, is there a clean way to force the page to reload if you link to the current page, or change the url?
currently I am using jQuery to set the window.location with the new variables then reloading the page.
also, I have a similar problem for using the back button on the browser. It will change the url but not refresh the page, so if you have a variable set to 1 you change it to be 2, that works and the page will reload with the variable set o 2, but if you go back using the browser history the url will say that your variable should be 1, but the rest of the page will still act like the variable is 2, until you refresh the page.
is there someway to set a page so that the it will automatically refresh when you go to the page from the same page, either through links or going forward or backward with the browser history?
as per request here is part of the parts of the code I am having problems with:
first is the code for the creating the html elements onload
var sel_tags=document.getElementsByName("selected_tags")[0];
var temp="";
if(Tags==null)
{
temp="\<p>All Notes\<\/p>";
}
else//Tags not empty, and there are tag filters
{
var click= new Array("",a+ AtTagShow);
var GoTo="PageViewNotes.html?"
for (var i=0; i < Tags.length; i++) {
//if we are showing #tags, or a tag is not an #tag
if(AtTagShow||Tags[i][0]!="#")
{
click[0]=t+Tags[i];
if (temp.length>0)
{temp+="\<span class=\"spacer\">\/<\/span>"};
temp+="\<a class=\"selected_tags_label\""+
"href=\""+GoTo+click.join("&")+"\">\<span>"
+Tags[i]+"\<\/span>\<\/a>"
}
};
};
sel_tags.innerHTML=temp;
here is the jquery code for setting the onclick:
$(".selected_tags_label").live("click",function(){
window.location=(this.href);
window.location.reload();
});
an example url for this issue would be:
page.html?Tags=#rediculous,#meeting&AtTagShow=true
by clicking on the rediculous element the url would change to:
page.html?Tags=#rediculous&AtTagShow=true
window.location.href="page.html?Tags=#rediculous&AtTagShow=true"
Take a look at the jQuery History plug-in for setting your site up to have back / forward history. It helps with setting up states on your page, that call data based on what query parameters are in the URL string.
In modern browsers (IE8+, Opera 10.6+, Fx 3.6+, Safari 5+) you have hashchange event.
Instead of reloading page, maybe you can achieve desired results with something like this:
<script>
document.onhashchange = function(){
// do something
}
</script>
MDN might be also helpful.
If you are using query parameters (things after the ? mark in the URL), then changing a query parameter and setting window.location to that new URL should cause a new page load from the server.
If you are using hash values (things after the # mark int he URL), then changing the hash value will not cause a new page load.
So, if you want a fresh page load from server each time you change a value, then you should be using query parameters. Back and forward should also work fine when using query parameters.
If you're purposely trying to do all of this with hash values to avoid an actual server page reload, then you will have to do more coding to intercept hash changes and process them. That is easier to do in modern browsers than older browsers using the window.onhashchange event. See this page on MDN for more info.
Browser reloads the page, whenever any of these parts of the URL are updated via window.location:
Domain
Port
Path
Query string
But it won't load the current document, if you change the fragment_id part (which is simply a reference to an HTML element inside the current document).
Thus from what you say, I guess you're updating the fragment id.
Also this might help to know that window.location.reload() method does the work of F5 key.

Prevent iFrame from changing location?

I've got a simple app that parses Tumblr blog templates. It's modeled after their customization screen and contains a header with some configurable options and an iframe. Every time an option changes, the app reloads the iframe, serializing the config form and updating the iframe's src with the serialized data as a query string.
This all works fine, except every time this happens, I am only able to reload the main index page with the changed options. If the user wants to view, say, a single post page by navigating away from the index, the template renders that page, only with the default options.
In other words, the changed options do no persist while the user navigates the blog.
I've been able to have 'persisting changes' with an $('iframe').load() event like so:
$('iframe').load(function(){
updateTheme();
});
The only problem is, as you can tell, this would wait for the iframe to fully render the page using the default options, then re-renders it with the updated options. I mean... it works, but it's not really a great solution.
Does anybody know how I can prevent the iframe from loading, capturing the users desired location, then re-render the frame with the current options as represented in the header?
Any help would be greatly appreciated. Thanks in advance!
Are you hosting both the top-level page and the embedded iframe page? If so, there are some games you can play, but it's not pretty. For example you can rewrite links within the embedded iframe in order to pre-fill the config options, e.g. with something like:
$('iframe').load(function(){
$('a', $('iframe')).each(function() {
var new_url = this.attr("href");
new_url += config_options;
this.attr("href", new_url);
});
});
Here's what I came up with:
var p = top || parent;
(function($){
$('a').click(function(e) {
var prevent = e.isDefaultPrevented(),
is_local = p.isLocal(this.href),
is_hash = $(this).attr('href').match(/^#/);
if(prevent || ! is_local || is_hash) return;
e.prevenDefault();
p.updateTheme(this.href);
return false;
});
})(jQuery);
My worry was that I would be affecting the javascript events attached to <a/> tags by the user, but apparently jQuery will detect default prevented events, even if they weren't prevented with jQuery itself. I tested it like this:
document.getElementById('test-link').onclick = function() {
return false;
}
jQuery detects that the original event has been prevented, so I am just assuming I shouldn't continue.

Jquery - tell when the hash changes?

I'm trying to make my site respond correctly to the back button. I've saved that hash of what I want it to do, but I don't know the hook for jQuery to be able to tell when the hash changes. It's not .ready(), because the page doesn't reload. What do I use?
Edit for a bit of clarity:
I'm using an iframe, so I can't tell when someone clicks a link. It's on the same subdomain, so i'm able to see it's filepath, and am saving it so you can bookmark. Unfortunately by saving it as a hash, my back button now fails to reload, which fails to reload the iframe, so my back button is essentially broken. If there was a way to tell when the URI changes, I could check it against the iframe address and change it if they don't match.
All I need is a way to check if the URI has changed. Is there a .change() for the URI? Something along those lines?
You can try History Event plugin.
After the document is ready, you examine the hash and alter the page appropriately.
I don't know the hook for jQuery to be able to tell when the hash changes
You can intercept your hash anchors' click events and respond appropriately as opposed to waiting for a "the hash has changed" event (which doesn't exist).
Some approaches create a "the hash has changed" event by inspecting window.location.hash on a timer.
Ben 'the cowboy' Alman wrote a cross platform plugin for hash changes
http://benalman.com/news/2010/07/jquery-hashchange-event-v13/
I dont know if your using it inside of the iframe or what, but if you were to use it outside the iframe it would be like
$(function(){
$(window).hashchange(function(){
//Insert event to be triggered on has change.
changeIframeContent(window.location.hash);
})
})
You should have a look at the solution of Ben Nadel which is in binding events to non-DOM objects.
There is'nt a buitin way to watch for hash changes, in firefox you could use watch method, but as far as I know it isnt default, so you can hack it writing something like (see below)
function setWatchHashChanges(functionObject)
{
if(window.location.watch)
{
window.location.watch('hash', function(e){functionObject(e);return e;});
} else {
if(!setWatchHasnChanges.hash)
{
setWatchHasnChanges.hash = window.locaton.hash;
} else {
setInterval(function(){
if(setWatchHasnChanges.hash!== window.locaton.hash)
{
setWatchHasnChanges.hash = window.locaton.hash;
functionObject(setWatchHasnChanges.hash);
}
}, 100);
}
}

Is there a way to catch the back button event in javascript?

Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the hashchange event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.
What I ended up doing was creating an object as such:
var pageload = {
ignorehashchange: false,
loadUrl: function(){
if (pageload.ignorehashchange == false){
//code to parse window.location.hash and load content
};
}
};
Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:
window.addEventListener("hashchange", pageload.loadUrl, false);
Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:
pageload.ignorehashchange = true;
and then the following line after each hash modification line:
setTimeout(function(){pageload.ignorehashchange = false;}, 100);
So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.
Check out history.js. There is a html 5 statechange event and you can listen to it.
onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.
Did you took a look at this? http://developer.yahoo.com/yui/history/

Categories

Resources