Last active
August 29, 2015 14:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// author: [email protected] | |
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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