jquery-element-onresize demo
jquery-element-onresize is a simple jQuery plugin for detecting ALL changes in a size of ANY positioned element
HTML
<script src="https://rawgit.com/rbtbar/jquery-element-onresize/master/jquery-element-onresize.js"></script>
<h2>jquery-element-onresize demo: resize the window and/or use buttons to resize the grey box. The actual size will be displayed below.</h2>
<h3 id="monitor"></h3>
<input type="button" class="js-changer" value="Enlarge" data-factor="105" />
<input type="button" class="js-changer" value="Shrink" data-factor="95" />
<input type="button" id="destroyer" value="Disable plugin" />
<div id="wrapper">
<div id="monitoredElement">
We monitor the size of this box.
</div>
</div>
CSS
/* (0) the monitored element must be a positioned element (position is other than static) */
#monitoredElement {
position: absolute;
top: 25%;
left: 25%;
width: 25%;
height: 25%;
background-color: #808080;
}
#wrapper {
position: absolute;
top: auto;
height: 100%;
left: 0;
right: 0;
}
h2 {
color: #808080;
}
JavaScript
$(function () {
var $monitor = $("#monitor")
, $monitoredElement = $("#monitoredElement");
// (2) use the detectResizing plugin to monitor changes of element's size:
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });
// (3) write a function to react on changes:
function monitoredElement_onResize() {
var width = $monitoredElement.width()
, height = $monitoredElement.height();
$monitor.html("Current size: " + width + "px x " + height + "px");
}
$("input.js-changer").click(function () {
var width = $monitoredElement.width()
, height = $monitoredElement.height()
, factor = $(this).data("factor")
, parentWidth = $monitoredElement.offsetParent().width()
, parentHeight = $monitoredElement.offsetParent().height();
$monitoredElement.width(((width * factor) / parentWidth) + "%").height(((height * factor) / parentHeight) + "%");
});
$("#destroyer").click(function () {
if ($monitoredElement.data("plugin_detectResizing")) {
// (4) destroy the plugin:
$monitoredElement.data("plugin_detectResizing").destroy();
$(this).val("Enable plugin");
} else {
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });
$(this).val("Disable plugin");
}
});
});