I'm using Jquery/Ajax to load html pages into a div on my website. I get links certain class to open up in the specified div. When doing this the address bar remains www.example.com. Due to the fact that I do have several pages that I will like to be able to share; so when people visit the links it will take them to the website but with the specific page loaded into the div container.
Here's a few lines of my code
$( document ).ready(function() {
$.ajax({
method: 'GET',
url: "pages/promo.html",
success: function(content)
{
$('#contentarea').html (content);
}
});
});
$('.menu_nav') .click (function () {
var href = $(this) .attr('href');
$('#contentarea').hide() .load(href).slideDown( 'very slow' )
return false;
});
Unless the other pages are on your domain, you cannot do this. If the other pages are, see this StackOverflow question: Updating address bar with new URL without hash or reloading the page.
Here's the deal: since you are loading a new page and you want the URL of the browser to point to that page, you should just give users a link. They know how to use the back button. (You could use the information in the linked answer to to change the URL to something like this: http://www.trillumonopoly.com/other-website.com.)
You can use the history object.
$('#contentarea').html(content);
history.pushState({url: "pages/promo.html"}, "", "pages/promo.html");
With the use of the state {url: "pages/promo.html"} you can load your page into your div when your users navigate back/forward.
$(window).on("popstate", function(e) {
if (e.originalEvent.state != null)
{
// AJAX load e.originalEvent.state.url
}
})
Related
I am working on building a website that will not reload to a new page every time a link is pressed. I want to make something kind of like all enterprise/popular websites. (When looking in the network dev tab: notice that youtube page doesn't completely reload when you click on a link, same with google, same with Facebook for the most part. They all usually just reload the page content and nothing else.)
I would like only the HTML between the body tags to be changed (nothing else: no js,css, no head tags, etc).
It would seem like it is pretty easy. Currently, I am just using ajax to go out and fetch the html of the page, and load that into the body. Done! Not so fast... Three things (my code is at the bottom)
The js includes are located at the bottom of the page, right before the closing body and html tags. When looking in the network tab, it shows that the same js is always gotten again and parsed again. How do I prevent that?
Some pages will not load styles that are set. (note that all css, js, etc. scripts are the same for every page)
I want to make sure that the page is completely reloaded if the user leaves the website.
I am not sure if I am looking for a fix to the way I am doing it, but probably just a completely better different way to do it.
Here is my code:
$('a').on('click', function () { //on click of any <a> tag
var where = $(this).attr('href'); //gets url of the <a> attribute
$.ajax({
type: "GET",
url: where, //where is the variable defined above
success: function(a) {
// load next page
history.pushState({urlPath: where},"",where); //changes the link of the webpage
$('body').html(a); //changes the body of the webpage
document.title = $('#title').text(); //changes the title using some weird irrelevant method
}
});
return false;
});
$(window).on('popstate', function() {//on click of the back or forward button
$.ajax({
type: "GET",
url: window.location.href, //the url is the url that the back or forward button is set to
success: function(data) {
//console.log();
$('body').html(data);//replaces data
document.title = $('#title').text();//changes title using weird irrelevant method
}
});
});
I had created a pagination with ajax. When user click the page number, it called the ajax function. I want to remember the previous ajax html data when user hit the back button. Therefore, I am trying to add the hash to each page. eg. when user click page 3, url is www.site.com/#3, page 4, is www.site.com/#4. It works OK so far. However, when I click the back button, it always load the second last page no matter the hash is 3 or 4. So, how can I make sure each hash attach to the ajax's update content? if the url is www.site.com/#4, it will always load the page 4 content. Appreicate.
$('#pagination a').click(function(e){
e.preventDefault();
$this = $(this).attr('href');//href is the page number
var data = {
action: 'post_pagination_ajax',
post_num : $this,
};
$.ajax({
url: ajax_front_gallery.ajaxurl,
type:'POST',
data: data,
success: function(data){
$('.post-content').html(data);
}
});
window.location.hash = $this;
return false;
});
You have a click event, however when you hit back button there is no any click event, browser just loads previous page from history. So what you have to do is to make also a load event. Final result will look something like this:
function loadContent ( url,data ) {
$.ajax({
url: url,
type:'POST',
data: data,
success: function(data){
$('.post-content').html(data);
}
});
}
$('#pagination a').click(function(e){
e.preventDefault();
var hash = $(this).attr('href');
var data = {
action: 'post_pagination_ajax',
post_num : $(this).attr('href')
};
loadContent( ajax_front_gallery.ajaxurl,data );
window.location.hash = hash;
return false;
});
$( window ).load(function() {
var data = {
action: 'post_pagination_ajax',
post_num : window.location.hash
};
loadContent( ajax_front_gallery.ajaxurl,data );
});
Edit:
Even though this solves your problem i would recommend doing it other way. Since you change hash and want to load content based on hash. There is a hashchange event for that. So you could do:
$(window).hashchange( function(){
var data = {
action: 'post_pagination_ajax',
post_num : location.hash
};
loadContent( ajax_front_gallery.ajaxurl,data );
});
//Trigger hash-change if page laoded with existing hash
$(window).hashchange();
And you won't need any click event on a preventing the default behaviour, because default behaviour of changing hash in url is what you want.
So I am not really sure if there is a standard how browser handle the url fragment (hash). The problem is that setting the hash is originally used for saying the browser where to scroll (with anchors etc.: http://www.w3schools.com/jsref/prop_loc_hash.asp). So when you set the hash most browser will put a new state in the history but will not use the current state of the DOM but use the old one before the hash was set.
But I can say, when ever I implement asynchrone paging with Javascript I do it similiar like you do, but I check the hash on the page load and load the specific page, so you always have the result you want.
I think this is the way the Google search works and it was the source of my idea.
I made the contents of the page change using Ajax, but the problem is the site url stays the same, therefore it doesn't load the page at all, just the text on it. So for example, I click on the Login link and the content changes, but the url stays on site/, not site/login. The actual login form does not load because it doesn't even call it, only loads basic text. How can I fix that ?
P.S. Using Zend for the website
Script:
$(document).ready(function() {
$('a').click(function() {
var toLoad = $(this).attr('href');
$('#content').load(toLoad);
return false;
});
});
Ajax does not reload the page or load another page so the url does not change when you make an ajax request.
If you want the url to change, for example so that your ajax-filled pages can be shared and bookmarked, you need to change the url manually.
You can use the html5 history API for that.
A simple example:
// we need the click event here
$('a').click(function(e) {
// cancel default click action using `e`
e.preventDefault();
var toLoad = $(this).attr('href');
$('#content').load(toLoad);
// check if the html5 history api is available in the browser first
if (window.history && window.history.pushState) {
// push the state to the url in the address bar
history.pushState({}, e.target.textContent, e.target.href);
}
});
Now the url in the address bar should change to the url of the link but the link is not really followed, instead the ajax request was made.
Note that you also need to make sure that all your urls load correctly. This is just a simple example and by the look of it your linked url would not load a complete page.
Check for example the documentation on mozilla.org for more information.
I am trying to create a webpage that will dynamically fill a div using AJAX. I have been able to simply update the div content with the following AJAX code:
$(document).ready(function(){
$("#projects-list a").click(function(e){
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$('#content').fadeOut(300, function() {
$('#content').html(data).delay(200).fadeIn(300);
});
}
});
});
});
However, I also am hoping to find a way to update the page URL or change the hash. So for instance, when a user is given the link to /projects.html they will be sent to a page of links, and then when a link is clicked the content is changed using AJAX and the url will change to /projects.html#first. This way then a user navigates to /projects.html#first they will see the content for the first project rather than the original list of projects to choose from.
I would recomend to use a library to handle URL and paths
http://github.com/flatiron/director
http://balupton.github.com/history.js/demo
if you want to use standard # then you can use via js, on a function call do :
window.location.hash = valueYouWantToSet, some ID mostly,
and then you can check on page load if there is a # in there then call a particular function like :
handleHash: function () { if (!isNaN(parseInt(window.location.hash.replace('#', '')))){ this.showDetails(window.location.hash.replace('#', '')); }
I have a jQuery script that loads content into a div. When you click on a menu item, the content gets loaded inside of "contentarea" and the URL gets updated. That part works perfectly. However, I would also like to be able to click inside of the div (once content has been loaded into it), and load another page in its place. For example, the Forms page gets loaded into contentarea, and inside of the forms page there is a link to the contact us page. When I click on the link, I would like for the forms page to be cleared from content area and the contact us page to be loaded in its place. See the following image:
With the way my script is setup right now, content only loads when I click from outside of the div.
Here's the code I need to modify:
<script type="text/javascript">
//Jquery loader
function getHash() {
return window.location.hash
}
$("a").on("click", function (e) {
page = this.href.replace("#", "") + ".html",
hash = $(this).prop("hash");
$('#contentarea').load(page, function () {
if (page.match("home.html")) {
history.pushState('', document.title, window.location.pathname);
} else {
location.hash = hash;
};
});
});
//on pageload
history.pushState
var hash = getHash();
if (hash) {
$("a[href='" + hash + "']").trigger("click");
} else {
$("a[href='#home']").trigger("click");
}
</script>
Any help would be greatly appreciated!
Since you are using jQuery, i would propose this:
$(document).ready(function() {
$(document).on( 'click', 'a', function( e ) {
$('#contentarea').load( e.target.href );
});
});
But if you are creating an app, and you are applying it globally, in your case i would reconsider your structure to avoid major changes on your code later. I've passed on that, because you have to manage states (variables of page/state if they exist: like errors, title, url, and obviously content) and determine which of them is active or not to pass to next page or not. Then you have to filter links that you don't want to propague to your history states handler cause you just don't want to...
On some cases, you can't apply existent frameworks on your project because the best approach is to use their code on your framework (yes, create your own framework).
I hope this could help you! :)