Convert Absolute Position To Relative Using Jquery
Published on May 26, 2013
Recently when i am working on a project i need to convert all relative position divs into absolute position with out loosing it’s actual look. My actual plan is to create jQuery Masonry like plugin with animations(that’s another story). But now in this post i want to share a simple jquery plugin I developed to convert relative positioning divs into Absolute positioning divs.
HTML
<html>
<head>
<script
type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
></script>
<style>
#main {
width: 800px;
margin: 0 auto;
}
.iteam {
height: 100px;
width: 100px;
margin: 10px;
background: blue;
float: left;
}
</style>
</head>
<body>
<div id="main">
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
<div class="iteam"></div>
</div>
</body>
</html>
How to use this plugin
<script type="text/javascript" src="r2a.js"></script>
<script type="text/javascript">
$('#main').r2a({ child: '.iteam' });
</script>
r2a.js
/*--------------------------------------------------------------------------------------------
| @desc: Relateive to Absolute
| @author: Aravind Buddha
| @url: //www.techumber.com
| @date: 26 MAR 2013
| @email: aravind@techumber.com
| @license: Free! to Share,copy, distribute and transmit ,
| but i'll be glad if my name listed in the credits'
---------------------------------------------------------------------------------------------*/
(function($, window, document, undefined) {
var pluginName = 'r2a',
defaults = {
child: '.box',
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.ParentHeight = '';
this.init();
}
Plugin.prototype = {
init: function() {
this.dor2a();
},
dor2a: function() {
this.ParentHeight = $(this.element).height();
$(this.element).css({ position: 'relative', height: ph });
$(this.element)
.find(this.options.child)
.each(function() {
var t = $(this).position().top;
var l = $(this).position().left;
$(this).css({ top: t, left: l });
});
$(this.options.child).css({ position: 'absolute' });
},
};
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
The logic is petty simple first we will find top and left position of the each child div and add those values through jquery’s css function. After that we will change the position to absolute. That’s it.