Gracefully redirect users after a long(minutes) interval - html

So, this is a pretty simple sounding question, but I'm interested in other peoples opinions about the "best" practice for handling this. The site is a presentational delivery of building energy information; it's mostly HTML5/CSS3 and jQuery with some heavy graphics. It does use PHP to leverage the building information via an API, however it does not drive any other attribute of the site.
So, this site needs to do one last thing, after a set interval(usually several minutes long) the page needs to redirect the user to the next page in the flow. It's important that the browser also refreshes periodically(to restart looping animations).
I've certainly considered the very simple:
<html>
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "../javascriptredirect.php"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 300000)">
</body>
</html>
This works, but it doesn't "feel" like the best option. Thanks in advance to anyone who can contribute an idea.

You can also use the meta refresh tag, which doesn't rely on JavaScript.
<meta http-equiv="refresh" content="300000;url=http:/yourdomain.com/javascriptredirect.php" />
The downside to this is that if you need to interact with this redirect or cancel it, since it's not JavaScript bound, you can't do anything with it.
As for the other part of your question about the page also needing to refresh occasionally to restart animations, I would recommend using JavaScript to do this after a given amount of time instead of refreshing the page. The reason for this is that if you refresh the page, the redirect "timer" restarts, meaning that if your refresh is sooner than your redirect, you will never redirect.

I think your method would work best. When you refresh the page with code, you could add a querystring parameter to the url and on page load if you detect that parameter there, then you know it has refreshed already and you may then decide to redirect after a couple of page refreshes.
function delayer(){
var refresh_value = getQuerystring('r')
if(refresh_value == '')
window.location = "../samepage.php?r=1"
if(refresh_value == '1')
window.location = "../samepage.php?r=2"
if(refresh_value == '2')
window.location = "../javascriptredirect.php"
}
Function pulled from: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
If this had been earlier in development I would suggest loading content of another page, slide out your current content then slide in the new content. That would have opened the door to easily trigger page refreshes, too. When I think of a website as a slideshow I think of jquery mobile. When you click on a link in jqmobile, it loads the next page's content in to the current DOM, then it slides out the old content and slides in the new content. Upon loading the new content, a hash-tag is appended to the url so, it helps to image how it is really just referencing another block of content on the same page (like when using Go to Paragraph 2).

Related

How can i add a link to a button? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How can I redirect the user from one page to another using jQuery or pure JavaScript?
One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
location.href
If you want to simulate an HTTP redirect, use location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).prop('href', 'http://stackoverflow.com')
Standard "vanilla" JavaScript way to redirect a page
window.location.href = 'newPage.html';
Or more simply: (since window is Global)
location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.
Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
This works for every browser:
window.location.href = 'your_url';
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.
Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.
Sample code without delay looks like this:
<!-- Place this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.
JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..
var currentLocation = window.location;
Basic Structure of a URL
<protocol>//<hostname>:<port>/<pathname><search><hash>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.
query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
hash -Sets or returns the anchor portion of a URL.
host -Sets
or returns the hostname and port of a URL.
hostname -Sets or
returns the hostname of a URL.
href -Sets or returns the entire
URL.
pathname -Sets or returns the path name of a URL.
port -Sets or returns the port number the server uses for a URL.
protocol -Sets or returns the protocol of a URL.
search -Sets
or returns the query portion of a URL
Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this
You can use the href property of the Location object.
window.location.href = "http://www.stackoverflow.com";
Location Object also have these three methods
assign() -- Loads a new document.
reload() -- Reloads the current document.
replace() -- Replaces the current document with a new one
You can use assign() and replace methods also to redirect to other pages like these
location.assign("http://www.stackoverflow.com");
location.replace("http://www.stackoverflow.com");
How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.
You can change the location object href property using jQuery also like this
$(location).attr('href',url);
And hence you can redirect the user to some other url.
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
Should just be able to set using window.location.
Example:
window.location = "https://stackoverflow.com/";
Here is a past post on the subject: How do I redirect to another webpage?
Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.
A quote from Jquery.com:
While jQuery might run without major issues in older browser versions,
we do not actively test jQuery in them and generally do not fix bugs
that may appear in them.
It was found here:
https://jquery.com/browser-support/
So jQuery is not an end-all and be-all solution for backwards compatibility.
The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.
This page will redirect to Google after 3000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
Different options are as follows:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.
You can also use meta data to run a page redirect as followed.
META Refresh
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):
https://code.google.com/p/html5security/wiki/RedirectionMethods
I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.
The next paragraph is hypothetical:
You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.
Please review Google Webmaster Guidelines about redirects:
https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971
Here is a fun little page that kicks you out of the page.
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.
var url = 'asdf.html';
window.location.href = url;
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
This works with jQuery:
$(window).attr("location", "http://google.fr");
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";.
Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.
To just redirect to a page with JavaScript:
window.location.href = "/contact/";
Or if you need a delay:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
So, the question is how to make a redirect page, and not how to redirect to a website?
You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
So say you just put this snippet into a redirect/index.html file on your website you can use it like so.
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
And if you go to that link it will automatically redirect you to stackoverflow.com.
Link to Documentation
And that's how you make a Simple redirect page with JavaScript
Edit:
There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.
Example:
The process: store home => redirect page to google => google
When at google: google => back button in browser => store home
So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this
if( url ) window.location.replace(url);
with
if( url ) window.location.href = url;
You need to put this line in your code:
$(location).attr("href","http://stackoverflow.com");
If you don't have jQuery, go with JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
On your click function, just add:
window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
window.location.href = "http://www.google.com";
});
Try this:
location.assign("http://www.google.com");
Code snippet of example.
jQuery is not needed. You can do this:
window.open("URL","_self","","")
It is that easy!
The best way to initiate an HTTP request is with document.loacation.href.replace('URL').
Using JavaScript:
Method 1:
window.location.href="http://google.com";
Method 2:
window.location.replace("http://google.com");
Using jQuery:
Method 1: $(location)
$(location).attr('href', 'http://google.com');
Method 2: Reusable Function
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
JavaScript is very extensive. If you want to jump to another page you have three options.
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
As you want to move to another page, you can use any from these if this is your requirement.
However all three options are limited to different situations. Chose wisely according to your requirement.
If you are interested in more knowledge about the concept, you can go through further.
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
In JavaScript and jQuery we can use the following code to redirect the one page to another page:
window.location.href="http://google.com";
window.location.replace("page1.html");
ECMAScript 6 + jQuery, 85 bytes
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr() on the location or window objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.
The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
Jquery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
Here is a time-delay redirection. You can set the delay time to whatever you want:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>

Search input field not opening in same tab [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How can I redirect the user from one page to another using jQuery or pure JavaScript?
One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
location.href
If you want to simulate an HTTP redirect, use location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).prop('href', 'http://stackoverflow.com')
Standard "vanilla" JavaScript way to redirect a page
window.location.href = 'newPage.html';
Or more simply: (since window is Global)
location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.
Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
This works for every browser:
window.location.href = 'your_url';
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.
Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.
Sample code without delay looks like this:
<!-- Place this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.
JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..
var currentLocation = window.location;
Basic Structure of a URL
<protocol>//<hostname>:<port>/<pathname><search><hash>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.
query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
hash -Sets or returns the anchor portion of a URL.
host -Sets
or returns the hostname and port of a URL.
hostname -Sets or
returns the hostname of a URL.
href -Sets or returns the entire
URL.
pathname -Sets or returns the path name of a URL.
port -Sets or returns the port number the server uses for a URL.
protocol -Sets or returns the protocol of a URL.
search -Sets
or returns the query portion of a URL
Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this
You can use the href property of the Location object.
window.location.href = "http://www.stackoverflow.com";
Location Object also have these three methods
assign() -- Loads a new document.
reload() -- Reloads the current document.
replace() -- Replaces the current document with a new one
You can use assign() and replace methods also to redirect to other pages like these
location.assign("http://www.stackoverflow.com");
location.replace("http://www.stackoverflow.com");
How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.
You can change the location object href property using jQuery also like this
$(location).attr('href',url);
And hence you can redirect the user to some other url.
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
Should just be able to set using window.location.
Example:
window.location = "https://stackoverflow.com/";
Here is a past post on the subject: How do I redirect to another webpage?
Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.
A quote from Jquery.com:
While jQuery might run without major issues in older browser versions,
we do not actively test jQuery in them and generally do not fix bugs
that may appear in them.
It was found here:
https://jquery.com/browser-support/
So jQuery is not an end-all and be-all solution for backwards compatibility.
The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.
This page will redirect to Google after 3000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
Different options are as follows:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.
You can also use meta data to run a page redirect as followed.
META Refresh
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):
https://code.google.com/p/html5security/wiki/RedirectionMethods
I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.
The next paragraph is hypothetical:
You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.
Please review Google Webmaster Guidelines about redirects:
https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971
Here is a fun little page that kicks you out of the page.
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.
var url = 'asdf.html';
window.location.href = url;
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
This works with jQuery:
$(window).attr("location", "http://google.fr");
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";.
Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.
To just redirect to a page with JavaScript:
window.location.href = "/contact/";
Or if you need a delay:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
So, the question is how to make a redirect page, and not how to redirect to a website?
You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
So say you just put this snippet into a redirect/index.html file on your website you can use it like so.
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
And if you go to that link it will automatically redirect you to stackoverflow.com.
Link to Documentation
And that's how you make a Simple redirect page with JavaScript
Edit:
There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.
Example:
The process: store home => redirect page to google => google
When at google: google => back button in browser => store home
So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this
if( url ) window.location.replace(url);
with
if( url ) window.location.href = url;
You need to put this line in your code:
$(location).attr("href","http://stackoverflow.com");
If you don't have jQuery, go with JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
On your click function, just add:
window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
window.location.href = "http://www.google.com";
});
Try this:
location.assign("http://www.google.com");
Code snippet of example.
jQuery is not needed. You can do this:
window.open("URL","_self","","")
It is that easy!
The best way to initiate an HTTP request is with document.loacation.href.replace('URL').
Using JavaScript:
Method 1:
window.location.href="http://google.com";
Method 2:
window.location.replace("http://google.com");
Using jQuery:
Method 1: $(location)
$(location).attr('href', 'http://google.com');
Method 2: Reusable Function
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
JavaScript is very extensive. If you want to jump to another page you have three options.
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
As you want to move to another page, you can use any from these if this is your requirement.
However all three options are limited to different situations. Chose wisely according to your requirement.
If you are interested in more knowledge about the concept, you can go through further.
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
In JavaScript and jQuery we can use the following code to redirect the one page to another page:
window.location.href="http://google.com";
window.location.replace("page1.html");
ECMAScript 6 + jQuery, 85 bytes
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr() on the location or window objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.
The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
Jquery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
Here is a time-delay redirection. You can set the delay time to whatever you want:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>

Keeping the basic layout same across the web pages

I have a website in which I finished with the basic layout, design, fonts, styles, css etc.
For almost whole of the website, the layout i.e the sidebar, the footer, the background etc. will remain the same. There are custom embedded fonts used as well.
Since this basic layout will remain the same all across the website, I wanted to ask how can I prevent downloading of this content (like side-bar, fonts, or javascript etc.) again for the user, so that the other pages after the start do not take as much time as the start page.
I am sure there would be some mechanism since most of the websites have header/footer/sidebar in common across the pages. My website is in plain html/css, and there's no backend being used. Any ideas?
Your images, fonts, css and other contents will most likely be cached by the client's browser on the first hit, so it will be downloaded just once.
For the html page itself, since you use static html content, the only way I can think of is using AJAX request.
You probably want to use includes. So on each page you'd have a header include, a footer include, a sidebar include and even an include containing links to your css/js files.
Simplest way to do this would be to change your pages to be .php pages and use php includes to pull in the header file, footer file etc.
You can static-site generator like Jekyll.
You may design a basic layout first.
Avoid inline and embedded CSS maximum and add a class (can assign to multiple) or id (can assign to single) to common selectors.
Make a master stylesheet like master.css and attach this to every page.
Hope this helps.
You can do this in two way. You say you don't have a backend, however the server where your website is hosted can be the backend.
Without any backend interaction:
If you really prefer not to use the backend at all, you can make this a single page website, with some javascript to switch the content you have in there. The idea is you have your website structure, and your default data available the way you normally have it right. But you also have the html for your other pages in hidden divs. Then when you want to switch to say the about link you use javascript to get the content from the hidden div with that content and you place that content in the main div.
<!--First lets use jquery thought it can use some other framework-->
<script src="http://code.google.com/apis/ajaxlibs/documentation/index.html#jquery"></script>
<script>
$('a[href=#myAboutPage]').on('click',function(){//Whenever link that points to #myAboutPage is clicked
var getHTMLFROM = document.getElementById('myAboutPageHiddenContent').innerHTML;
//And place it on main div
document.getElementById('mainDivContent').innerHTML = getHTMLFROM
});
</script>
If you wanted to use some ajax interactions:
The process would be the same with the exception that the getHTMLFROM content, would actually be an html file that you request from the server.
Both of this javascript oriented methods will work, but would NOT recommend if you want your information to be SEO friendly. With that said reuse an external piece of css, to minimize redownloading the styling of your interface every single time.
There are definitely many ways to do this. I am a fan of dynamic inclusion. Here is a link to a great tutorial which explains how to set it up for your own page very simply. Dynamic Inclusion Tutorial NOTE: Don't be afaid of PHP, or having to change your file extension to PHP. It won't change your coding experience at all. It will just enhance your abilities.
I also have used the Javascript feature to hide certain elements. Depending on the size of your website, it may be just as easy to reload your CSS and navigation elements. However, if you really don't want your menu and logo to blink momentarily while it is reloading, you can just hide/reveal elements very simply with a bit of JS.
Here is an example function from my website:
function toggleVisible(e){
var i = e.id;
if(e.className == 'collapsed')
{
e.className = 'expanded';
e.innerHTML = 'Hide'
var hiddenArray = document.getElementsByClassName('hidden' + i);
hiddenArray[0].setAttribute('class', 'expanded' + i);
}
else if (e.className == 'expanded')
{
e.className = 'collapsed';
e.innerHTML = 'Show More';
var expandedArray = document.getElementsByClassName('expanded' + i);
expandedArray[0].setAttribute('class', 'hidden' + i);
}
}
The above code will run when the following link is clicked:
ANYWEBSITE.com || <a onClick="toggleVisible(this)" id="4" class="collapsed">Show More</a> || View PDF
Also, another user mentioned caching. Caching appears to be unreliable. Check out the following links for more info:
AJAX cache
HTML5 Application cache
2009 article about browser caching from stackoverflow.com question

Injecting DIV-Tag at top of page AND Automatic start of script when page is loading?

I started to program my own Chrome extension today and I'm stuck since hours with one problem.
Right now, I'm sending the current URL from the open website to my server where it's checked against some criterias and then a return value is sent back to the extension. This is working so far. I'm using only a popup.html, no background page.
The request is only sent when the user clicks on the icon in the browser.
How can I realize that the request is automatically sent, when the page is loaded?
If there is a specific return value from the server the user should be given an unannoying warning. Alert boxes and new windows are...well...annoying. Best way should be the little popup under the icon of the extension but that's not possible without a user's click. So I thought of a little -layer at the top of the page.
<html>
<head>
<script>
window.addEventListener("load", sendRequest, false);
function sendRequest() {
var q = "test";
xmlHttp=new XMLHttpRequest();
xmlHttp.open('GET', 'http://www.testurl.com/check.php?q='+q, true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("textf").innerText = xmlHttp.responseText;
chrome.tabs.executeScript(null,{code:"<div style='position: absolute; top: 0; left: 0; background-color=blue;layer-background-color: blue;'><p>test </p><p>test2 </p></div>"});
}
}
xmlHttp.send(null);
}
</script>
</head>
<body>
//Just for the popup...
<font color="blue"><p id="textf">Checking...</p></font>
</body>
</html>
If I do
chrome.tabs.executeScript(null,{code:"alert('testalert')"});
it gives me the alert. However, the isn't working and I can't figure out why :(
Do I need a background page for all this since I only want to check the URL when the page is loaded?
Why is the -thing not working but the alert is?
Thank you in advance!
chrome.tabs.executeScript is for JavaScript only. To add content to a Web page, you must write JavaScript that manipulates the DOM. A good place for you to start learning this may be Mozilla's DOM docs. (DOM is a W3C standard and Chrome has implemented it, so yes, Mozilla pages are relevant here.)
If I may say so, it sounds like the best way forward for you is to scrap this and start over with a content script defined in your manifest so that Chrome will execute it for you; check the Content Scripts documentation to learn more. Since you're trying to accomplish your goal with no background page, and would therefore need to use XMLHttpRequest directly from your content script, you should add "minimum_chrome_version": "13" to your manifest, as Chrome 12 and earlier won't let you do that.
By the way, practically no one will understand what you're talking about when you use "-layer" and "-thing" like that. Please be more careful in making sure you are using proper terminology. Ask your peers if you're unsure of the proper term for something.

CodeIgniter + jQuery(ajax) + HTML5 pushstate: How can I make a clean navigation with real URLs?

I'm currently trying to build a new website, nothing special, nice and small, but I'm stuck at the very beginning.
My problems are clean URLs and page navigation. I want to do it "the right way".
What I would like to have:
I use CodeIgniter to get clean URLs like
"www.example.com/hello/world"
jQuery helps me using ajax, so I can
.load() additional content
Now I want to use HTML5 features like pushstate to
get rid of the # in the URL
It should be possible to go back and forth without a page refresh but the page will still display the right content according to the current URL.
It should also be possible to reload a page without getting a 404 error. The site should exist thanks to CodeIgniter. (there is a controller and a view)
For example:
A very basic website. Two links, called "foo" and "bar" and a emtpy div box beneath them.
The basic URL is example.com
When you click on "foo" the URL changes to "example.com/foo" without reloading and the div box gets new content with jQuery .load(). The same goes for the other link, just of course different content and URL.
After clicking "foo" and then "bar" the back button will bring me back to "example.com/foo" with the according content. If I load this link directly or refresh the page, it will look the same. No 404 error or something.
Just think about this page and tell me how you would do this.
I would really love to have this kind of navigation and so I tried several things.
So far...
I know how to use CodeIgniter to get the URLs like this. I know how to use jQuery to load additional content and while I don't fully understand the html5 pushstate stuff, I at least got it to work somehow.
But I can't get it to work all together.
My code right now is a mess, that's the reason I don't really want to post it here. I looked at different tutorials and copy pasted some code together. Would be better to upload my CI folder I guess.
Some of the tutorials I looked at:
Dive into HTML5
HTML5 demos
Mozilla manipulating the browser history
Saner HTML5 history
Github: History.js
(max. number of links reached :/)
I think my main problem is, that everybody tries to make it compatible with all browsers and different versions, adds scripts/jQuery plugins and whatnot and I get confused by all the additional code. There is more code between my script-tags then actual html content.
Could somebody post the most basic method how to use HTML5 for my example page?
My failed attemp:
On my test page, when I go back, the URL changes, but the div box will still show the same content, not the old one. I also don't know how to change the URL in the script according to the href attribute from the link. Is there something like $(this).attr('href'), that changes according to which link I click? Right now I would have to use a script for every link, which of course is bad.
When I refresh the site, CodeIgniter kicks in and loads the view, but really only the view by itself, the one I loaded with ajax, not the whole page. But I guess that should be easy to fix with a layout and the right controller settings. Haven't paid much attention to this yet.
Thanks in advance for any help.
If you have suggestions, ideas, or simple just want to mention something, please let me know.
regards
DiLer
I've put up a successful minimal example of HTML5 history here: http://cairo140.github.com/html5-history-example/one.html
The easiest way to get into HTML5 pushstate in my opinion is to ignore the framework for a while and use the most simplistic state transition possible: a wholesale replacement of the <body> and <title> elements. Outside of those elements, the rest of the markup is probably just boilerplate, although if it varies (e.g., if you change the class on HTML in the backend), you can adapt that.
What a dynamic backend like CI does is essentially fake the existence of data at particular locations (identified by the URL) by generating it dynamically on the fly. We can abstract away from the effect of the framework by literally creating the resources and putting them in locations through which your web server (Apache, probably) will simply identify them and feed them on through. We'll have a very simple file system structure relative to the domain root:
/one.html
/two.html
/assets/application.js
Those are the only three files we're working with.
Here's the code for the two HTML files. If you're at the level when you're dealing with HTML5 features, you should be able to understand the markup, but if I didn't make something clear, just leave a comment, and I'll walk you through it:
one.html
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script src="assets/application.js"></script>
<title>One</title>
</head>
<body>
<div class="container">
<h1>One</h1>
Two
</div>
</body>
</html>
two.html
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script src="assets/application.js"></script>
<title>Two</title>
</head>
<body>
<div class="container">
<h1>Two</h1>
One
</div>
</body>
</html>
You'll notice that if you load one.html through your browser, you can click on the link to two.html, which will load and display a new page. And from two.html, you can do the same back to one.html. Cool.
Now, for the history part:
assets/application.js
$(function(){
var replacePage = function(url) {
$.ajax({
url: url,
type: 'get',
dataType: 'html',
success: function(data){
var dom = $(data);
var title = dom.filter('title').text();
var html = dom.filter('.container').html();
$('title').text(title);
$('.container').html(html);
}
});
}
$('a').live('click', function(e){
history.pushState(null, null, this.href);
replacePage(this.href);
e.preventDefault();
});
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
});
How it works
I define replacePage within the jQuery ready callback to do some straightforward loading of the URL in the argument and to replace the contents of the title and .container elements with those retrieved remotely.
The live call means that any link clicked on the page will trigger the callback, and the callback pushes the state to the href in the link and calls replacePage. It also uses e.preventDefault to prevent the link from being processed the normal way.
Finally, there's a popstate event that fires when a user uses browser-based page navigation (back, forward). We bind a simple callback to that event. Of note is that I couldn't get the version on the Dive Into HTML page to work for some reason in FF for Mac. No clue why.
How to extend it
This extremely basic example can more or less be transplanted onto any site because it does a very uncreative transition: HTML replacement. I suggest you can use this as a foundation and transition into more creative transitions. One example of what you could do would be to emulate what Github does with the directory navigation in its repositories. It's an intermediate manoever that requires floats and overflow management. You could start with a simpler transition like appending the .container in the loaded page to the DOM and then animating the old container to {height: 0}.
Addressing your specific "For example"
You're on the right track for using HTML5 history, but you need to clarify your idea of exactly what /foo and /bar will contain. Basically, you're going to have three pages: /, /foo, and /bar. / will have an empty container div. /foo will be identical to / except in that container div has some foo content in it. /bar will be identical to /foo except in that the container div has some bar content in it. Now, the question comes to how you would extract the contents of the container through Javascript. Assuming that your /foo body tag looked something like this:
<body>
foo
bar
<div class="container">foo</div>
</body>
Then you would extract it from the response data through var html = $(data).filter('.container').html() and then put it back into the parent page through $('.container').html(html). You use filter instead of the much more reasonable find because from some wacky reason, jQuery's DOM parser produces a jQuery object containing every child of the head and every child of the body elements instead of just a jQuery object wrapping the html element. I don't know why.
The rest is just adapting this back into the "vanilla" version above. If you are stuck at any particular stage, let me know, and I can guide you better though it.
Code
https://github.com/cairo140/html5-history-example
Try this in your controller:
if (!$this->input->is_ajax_request())
$this->load->view('header');
$this->load->view('your_view', $data);
if (!$this->input->is_ajax_request())
$this->load->view('footer');