Search code examples
jqueryajaxhref

Write internal link with AJAX


I am trying to write some of my first jquery scripts but I'm having some problem... My page have a long text with lot of internal links ( <a href="/contents/Foo.htm" class=.internal>Foo</a> ). I'd like that when you click on one of the .internal links, the href path will be opened inside the <div id="article">.

var InternalLink = function() {
    $(".internal").click(function(){
        var path =  $(this).attr("href");
        $.ajax({
            url: "path",
            success: function(data) {
                $('#article').html(data);
            }
        });
    });    
};

I wrote the code shown below and it work perfectly but I am trying to generalize the code to every link with internal class:

$("#article_01").click(function(){
    $.ajax({
        url: 'contents/article_01.htm',
        success: function(data) {
            $('#article').html(data);
        }
    });
});

Solution

  • <a href="/contents/Foo.htm" class="internal" data-ref="article_01">Foo</a>
    

    JS:

    $(".internal").click(function(){
        var path =  this.href;
        var div = $(this).data('ref');
        $.ajax({
            url: path,
            success: function(data) {
                $('#'+div).html(data);
            }
        });
        return false; // so the link does *not* follow through
    });    
    

    So now all you have to do is change the data-ref to point to the div you want the html to load inside of.