Skip to content

Instantly share code, notes, and snippets.

@Nicola1971
Forked from aklump/jquery.iframe_to_div.js
Last active January 16, 2018 04:25
Show Gist options
  • Save Nicola1971/67cc8bd6d96c9550c204 to your computer and use it in GitHub Desktop.
Save Nicola1971/67cc8bd6d96c9550c204 to your computer and use it in GitHub Desktop.
/**
* Convert iframes to divs via ajax iframe_to_div jQuery Plugin
*
* Uses javascript to replace iframes with divs containing their source content
* by loading via ajax. If you use this to load vanilla html snippets, this has the
* effect of applying the page's css to your vanilla html snippet.
*
* This will not work if the iframe src is not a relative link due to ajax restrictions across domains.
*
* As an example:
*
* This html snippet is available at http://website/vanilla.html
* @code
* <!--this table has no styling on it's own, but when loaded via ajax, the
parent page's css will be applied magically!-->
* <table>
* <thead><tr><th>Unstyled header</th></tr></thead>
* <tr><td>Unstyled table cell</td></tr>
* </table>
* @endcode
*
* This is part of the index.html page
* @code
* <iframe src="/vanilla.html"></iframe>
* @endcode
*
* By adding the following js to index.html, the iframe is replaced with the
snippet from vanilla.html and the css of index.html is applied.
* @code
* $('body').iframe_to_div();
* @endcode
*
* Or you can target a specific iframe directly. The iframe has an id =
#my-replaceable-iframe
* @code
* $('#my-replaceable-iframe').iframe_to_div();
* @endcode
*
* @return $(this)
*
* @author Aaron Klump, In the Loft Studios, LLC
* @see http://www.intheloftstudios.com
* @see http://gist.github.com/aklump/5470863
*/
(function($) {
$.fn.iframe_to_div = function(options) {
var $context = $(this);
var settings = $.extend( {
'loading': 'Loading content...'
}, options);
if (!$context.is('iframe')) {
$context = $context.find('iframe:not(.iframe-to-div-processed)')
}
else if ($context.hasClass('iframe-to-div-processed')) {
return $(this);
}
$context.each(function() {
var $iframe = $(this);
var $loading = false;
if (settings.loading) {
$loading = $('<div><div class="inner">' + settings.loading + '</div></div>');
$iframe.after($loading.addClass('iframe-to-div-loading'));
}
$iframe.hide();
var src = $iframe.attr('src');
$.get(src, function(data) {
$iframe
.addClass('iframe-to-div-processed')
.replaceWith(data)
$loading.remove();
});
});
return $(this);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment