jquery recommended way to do ajax navigation - javascript

jquery recommended way to do ajax navigation
I just tried out this simple jquery ajax code to load all the links in a page in an ajax manner.
$('a').click(function(e){
e.preventDefault();
url = $(this).attr('href');
$('body').fadeTo('slow', 0.2);
$('body').load(url, function(data){
$(this).fadeTo('slow', 1, function(){
$(this).html(data);
scroll(0,0);
});
});
});
[The links in the page stick to the current domain and no external links are present]
The page load works as expected but the scripts for Facebook, LinkedIn, pinterest buttons fail to load.
I think this is not the safest way to do a ajax navigation and I am sure other JS files, inline JavaScripts will cause error.
http://davidwalsh.name has some good ajax navigation work with mootools. I am trying to achieve the same using jquery.
The website loads and executes every script successfully and it is seen that the ajax work is not done to load specific scripts.
Is there any safe way to achieve this, making sure that the ajax loaded page works as normal as it should ??

You should call the function that attaches the script inside the load handler, so it re-attaches all DOM scripts on each load.
F.ex, if you have this code:
$(document).ready(function() {
$('#facebook').doFacebook();
$('#twitter').doTwitter();
});
Change it to:
var onload = function() {
$('#facebook').doFacebook();
$('#twitter').doTwitter();
};
$(document).ready(onload);
Then just call onload whenever the body gets new content.
Inline scripts should execute according to the docs.
You might also want to read up on how to manipulate browser history and URL using .pushState:
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
There are decent jQuery plugins that adds this functionality in a cross-browser manner if you google around a bit.

Related

JavaScript in jQuery mobile not working unless I refresh

I'm having a jQuery mobile page with JavaScript inside. The problem is the JavaScript doesn't work unless the page is refreshed. Here is my code:
jQuery(function($) {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
To understand this problem you need to understand how jQuery Mobile works.
Your first problem is point where you are trying to initialize JavaScript. From your previous answers I can see you are using several HTML/ASP pages and all of your javascript is initialized form the page <head>. This is the main problem. Only the first HTML file should have JavaScript placed into the <head> content. When jQuery Mobile loads other pages into the DOM it loads only the <div> with a data-role="page" attribute. Everything else, including <head>, will be discarded.
This is because currently loaded page has a <head> already. No point in loading another pages <head> content. This goes even further. If you have several pages in a second HTML file, only the first one is going to be loaded.
I will not try to invent warm water here so here are links to my other 2 answers discussing this problem. Several solutions can be found there:
Why I have to put all the script to index.html in jquery mobile (or in this blog article)
Link fails to work unless refreshing
There's more then enough information there to give you an idea what to do.
The basic solutions to this problem are:
Put all of your JavaScript into a first HTML/ASP file
Move your JavaScript into <body>; to be more precise, move it into a <div> with data-role="page". As I already pointed out, this is the only part of a page that is going to be loaded.
Use rel="external" when switching between pages because it will trigger a full page refresh. Basically, you jQuery mobile that the page will act as a normal web application.
As Archer pointed out, you should use page events to initialize your code. But let me tell you more about this problem. Unlike classic normal web pages, when working with jQuery Mobile, document ready will usually trigger before page is fully loaded/enhanced inside the DOM.
That is why page events were created. There are several of them, but if you want your code to execute only once (like in case of document ready) you should use the pageinit event. In any other case use pagebeforeshow or pageshow.
If you want to find out more about page events and why they should be used instead of document ready take a look at this article on my personal blog. Or find it here.
Your question isn't exactly overflowing with pointers and tips, so I'm going with the thing that immediately sprung to mind when I saw it.
Document ready does not fire on page change with jQuery Mobile, due to "hijax", their method of "ajaxifying" all the links. Try this instead...
$(document).on("pageshow", function() {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
Try pageinit like this
$(document).delegate("body", "pageinit", function() { // Use body or page wrapper id / class
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
seems like nothing ever worked for me. Tried many different fixes, but i made the site too messy, that even position of certain javascript files wouldn't make the site work. Enough talk, here is what i came up with.
// write it in head at top of all javascripts
<script type="text/javascript">
$(document).ready(function() {
// stops ajax load thereby refreshing page
$("a,button,form").attr('data-ajax', 'false');
// encourages ajax load, hinders refresh page (in case if you want popup or dialogs to work.)
$("a[data-rel],a[data-dialog],a[data-transition]").attr('data-ajax', 'true');
});
</script>

Appending and loading a script on click jQuery / JavaScript

I currently have a site I am working on where there is a script that only needs to be loaded and shown when a certain element is clicked. The script we are loading is external and very slow to load and blocks the dom from loading as fast as it should. I am looking to append this script or load its contents into a certain element on click. I have looked high and low and have tried many different methods to do this with no success. I know this is possible and have done this before but cannot remember how.
Note that I have tried loading the contents of the url into an iframe then cloning and adding to the element.
The code below illustrates what I am looking to do
$("#button").click(function(e){
e.preventDefault();
var $slowLoadingScript = $('<script src="http://external-slow-script.com/script.js"></script>');
$slowLoadingScript.load(function(){
$("#Element").append(slowLoadingScript);
});
});
Note the contents of the script look like this:
document.write("a long list of html and js");
$('#button').click(function(e){
e.preventDefault();
$.getScript('http://external-slow-script.com/script.js');
});
Explanation for jQuery's $.getScript() at http://api.jquery.com/jQuery.getScript/.

Jquery colorbox - redirect/forward inside existing colorbox

So I have a colorbox loaded. I'd like to be able to redirect/forward to another page inside the existing colorbox.
window.location = href; won't work here.
EDIT: Being more specific, I want to intercept a form submit, and redirect if necessary.
$("#search-center-form").live("submit", function () {
alert('clicked');
$.post('myurl', function(data) {
console.log(data);
if (data) {
$.colorbox({href:'http://www.google.com/'});
}
}, 'json');
return false;
});
The original colorbox is opened up like so:
$.fn.colorbox({'href': block, 'open':true, 'inline':true, 'width':'530px', 'height':'260px'});
And now I'm trying to load an external URL into that colorbox. I suppose AJAX is an option but if you can load an iFrame in a colorbox, this should be possible too shouldn't it?
Thanks!
You're almost there, but there's a couple reasons why that code isn't working.
One is that you are trying to load content from another domain without the proper options. In order to do that, you need to set the iframe:true, width, and height. If you are loading content from your own domain, then you may not need the iframe option (and then colorbox will be able to automatically determine width and height). If all the necessary css or js is loaded, then you don't need it. If your new page has some css or js in its <head> that's not already loaded, then you'll need the iframe.
The other problem is not a mistake, but how google handles requests. Which is to say in the case of loading their site in an iframe, they don't; they will block the request, so you will not be able to use google with colorbox (without creative handling). Incidentally, although it's handled differently, stackoverflow won't allow it either, so don't bother putting that one in either.
In any case, your colorbox redirect (in your post callback) should look like this:
$.colorbox({href:'http://www.yahoo.com', iframe:true, width:"75%", height: "75%"});
have a look at the Inline HTML example on http://jacklmoore.com/colorbox/example3/

Document.ready script not working when page called into a tab

I have several pages that are called onto an ajax tabbed area. the pages that are called have javascript on them however the document.ready function will not load for each of these pages when loaded onto the tab. Instead I have had to put a button on the pages to load the function manually. Iv tried putting the document.ready function on both the page being called and the pages calling it but it still wont run. Is there any other way i can use rather than having a button? I dont want buttons displaying on my pages that have to be clicked before it looks good =(
Heres the code that calls the the page:
onclick="createNewTab('dhtmlgoodies_tabView1','Remote Access','','RemoteAccess.html',true);return false">Remote Access
All the javascript files are connected to the main page.
A button is located on the remoteaccess page:
input type='button' value='Load.' onclick='loadlightbox()'
The loadlightbox function is inside a javascript file that is conected to the main page:
loadlightbox = (function() {
$('#gallery a').lightBox({fixedNavigation:true});
});
There is no document.ready event being fired when you load the content into the page with JavaScript. Most libraries just stick what is returned with innerHTML. Most libraries just rip out the JavaScript code from the responseText and run it through eval().
You probably want to forget the whole document.ready and just stick the code block at the end.
The document.ready function won't fire because the page (document) is already loaded. The remote page is loaded as content not as a document.
Since you are using jquery you should take advantage of the .load function and also you should take a unobtrusive approach to attaching the onclick to your link. This allows your JS and code to be separate.
//Using Jquery load
$("#id_of_link").click(function(e){
e.preventDefault();
$('#dhtmlgoodies_tabView1').load("RemoteAccess.html",
function(){
//callback code here
})
})

using load() to load page that also uses jQuery

I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.
The problem is that inside of my "popup" form, I need to $(function()
{my function here}); syntax to do some stuff when the page loads,
along with registering some .fn extensions for some dynamic dropdowns
using ajax calls.
I have created my <script type="text/javascript" src="jquery.js"> but
I don't think these are being included, and also my $(function) is not
being called.
Is this possible to do or do I need to find another way of
accomplishing what I need to do?
If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.
So, you load the popup form like this:
$.ajax({
//...
success: function(text) {
// insert text into container
// the code from $(function() {});
}
});
The script isn't getting run because the document's ready event has already been fired. Remove your code from within the
$()
Use the livequery plugin.
It allows you to bind events to elements that might be loaded later: http://brandonaaron.net/docs/livequery/

Categories