Question

I haven't explained this well.

But what i mean is, if I have an ajax script that loads the content of a page in a DIV element, through the function 'loadpage('whatever.php');, instead of going around manually doing this to all links, is there a way of having a script that automatically makes all regular links load through that ajax function?

Like on Facebook, your profile loads through ajax, yet if you look at their code, they just have a regular link to the profile.

Cheers!

Was it helpful?

Solution

Sure, you can do it with jQuery.

This script goes through the document, finds every anchor element and binds an event handler to the click event of each. When the anchor element is clicked, the event handler finds the href attribute and loads that page into #targetDiv (you can call this div whatever you want, of course).

<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
  $("a").click(function() {
    $("#targetDiv").load(($(this).attr("href") + " body");
    return false;
  });
});
</script>

...

<!-- In your document body, this is the div you'd load the pages into. -->
<div id="targetDiv"></div>

OTHER TIPS

You can use JQuery for this (if I understand your question right).

First you can make the function loadpage() as follows:

function loadpage(divId, url) {
    $('#' + divId).load(url);

    return false;
}

.load() isn't supported by all browsers though. If you want to do this without .load() then you can check out .get(). For more info on .load(), take a look at http://docs.jquery.com/Ajax/load

I'm assuming it would go something like this:

$(document).ready(function(){
    $("a").click(function(){
        $("body").load($(this).attr("href") + " body");
        return false;
    });
});

This would make all <a> tags on the page call a function that downloads a HTML document from the href attribute of the tag, strip out it's body tag, and replace the contents of the current page's body tag with the contents of the new body tag. This way, it's easier to work this with no JavaScript, as well as integrate it into an existing site.

To use it, you place this into a <script> tag in the head of your main page, or in an external JS file.

Please note, however, that this code only updates the contents of the <body> tag, the head (including the title tag) remains untouched. You may need to add extra code to update things like this.

Simple and Nice. Check this out: Bjax

Usage:

<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />

Finally, include this in the HEAD of your html:

$('a').bjax();

For more settings, checkout demo here: Bjax Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top