diff --git a/README.md b/README.md index 33d9944..9c6f18a 100644 --- a/README.md +++ b/README.md @@ -7,18 +7,25 @@ A JavaScript plugin to contain an element within its parent element. * Pure JavaScript with no dependencies * Configures the horizontal and vertical alignment of the contained element * Can detect the native size or have it specified at runtime +* Includes function to update the size and position ## Usage ``` window.onload = function() { - containElement({ + var contain = new ContainElement({ id: 'element', // the id of the element to be contained width: '100', // (optional) element width in pixels (unset: element width) height: '100', // (optional) element height in pixels (unset: element height) valign: 'top', // (optional) vertical alignment: top|bottom (unset: middle) halign: 'left' // (optional) horizontal alignment: left|right (unset: middle) }); + + // (example) update the size and positioning on window resize + window.onresize = function(event) { contain.update(); }; + + // (example) update the size and positioning on orientation change + screen.addEventListener('orientationchange', function() { contain.update(); }); }; ``` diff --git a/contain-element.js b/contain-element.js index 1af648e..ccc8c7a 100644 --- a/contain-element.js +++ b/contain-element.js @@ -1,4 +1,4 @@ -function containElement(options) { +function ContainElement(options) { var scaleFactor = 1; var element = document.getElementById(options.id); var elementWidth = options.width || element.offsetWidth; @@ -12,7 +12,7 @@ function containElement(options) { if (element.parentElement.style.position != 'relative' && element.parentElement.style.position != 'absolute' && element.parentElement.style.position != 'fixed') element.parentElement.style.position = 'relative'; - function scaleElement() { + function updateContain() { var parentWidth = element.parentElement.offsetWidth; var parentHeight = element.parentElement.offsetHeight; @@ -67,13 +67,14 @@ function containElement(options) { } } else { // Try again in 30ms if the document didn't load enough to determine its width and height yet - window.setTimeout(scaleElement, 30); + window.setTimeout(updateContain, 30); } } // Run the scale function and bind it to various window-size-changing events - scaleElement(); - window.onresize = function(event) { scaleElement(); }; - screen.addEventListener('orientationchange', function() { scaleElement(); }); + updateContain(); + + // Add scale function to the library + this.update = function() { updateContain(); }; }