Search code examples
ajaxdynamicloadinghyperlinkdynamic-links

Is there a way of making normal links automatically load through ajax, rather than normally?


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!


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>