Skip to content

Instantly share code, notes, and snippets.

@teamaton
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamaton/7a64e38318ca0159333c to your computer and use it in GitHub Desktop.
Save teamaton/7a64e38318ca0159333c to your computer and use it in GitHub Desktop.
A jQuery plugin to move around HTML in your DOM and restore it when necessary
// author: oliver@teamaton.com
// LICENSE: MIT
(function($) {
$.fn.moveTo = function(target, method) {
method = method || "appendTo";
var randomNumber = Date.now().toString() + (10 ^ 6 * Math.random().toPrecision(6));
var placeholderId = "placeholder-" + randomNumber;
var $content = $(this).replaceWith("<script id='" + placeholderId + "' type='text/html'></" + "script>");
// same as $content.appendTo($(target)) but with variable method ;-)
$content[method]($(target));
$content.data("placeholderId", placeholderId);
}
$.fn.restore = function() {
var $content = $(this);
var placeholderId = $content.data("placeholderId");
if (!placeholderId) return;
var $destination = $("#" + placeholderId);
if ($destination.length === 0) {
console.error("Missing placeholder with id '' to restore content:", placeholderId);
return;
}
$destination.replaceWith($content);
}
})(jQuery);
<header>
Static header
</header>
<article>
<span id="title">My article is about web development</span>
</article>
<script src="jquery.tn.move-restore.js"></script>
<script>
// moveTo defaults to using $.fn.appendTo
$("#title").moveTo("header");
setTimeout(function() {
$("#title").restore();
}, 5000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment