Thursday, March 10, 2016

Use Bootstrap Popover to load external content through Ajax

It seemed easy to load an external contents through Ajax onto Bootstrap Popover at first. In fact, it wasn't as straightforward as I would like.
Using the content() function, it is straightforward to load any static content.
<a class="pop">Link</a>
<div id="contentDiv" style="display:none;">Some content...</div>

<script type="text/javascript">
$('.pop').popover({
    html: true,
    content: function(){
        return $('#contentDiv').html();
    }
});
</script>
However, loading an external content dynamically through Ajax plus "Loading ..." message took some thoughts.
<a class="pop" href="Product/100">Link</a>

<script type="text/javascript">
$('.pop').popover({
    html: true,
    content: function(){
        // Create a random temporary id for the content's parent div
        // with a unique number just in case.
        var content_id = "content-id-" + $.now();

        $.ajax({
            type: 'GET',
            url: $(this).prop('href'),
            cache: false,
        }).done(function(d){
            $('#' + content_id).html(d);
        });

        return '<div id="' + content_id + '">Loading...</div>';

        // Initially, the content() function returns a parent div, 
        // which shows "Loading..." message.
        // As soon as the ajax call is complete, the parent div inside 
        // the popover gets the ajax call's result.

    }
});
</script>

No comments: