Skip to content

Instantly share code, notes, and snippets.

@SimpleAnecdote
Created September 28, 2014 12:26
Show Gist options
  • Save SimpleAnecdote/d74412c7045d247359ed to your computer and use it in GitHub Desktop.
Save SimpleAnecdote/d74412c7045d247359ed to your computer and use it in GitHub Desktop.
Square element
/**
* Make an element's height equal to its width and sets an event handler to keep doing it
* @param {string} element - Selector of the element to make square
* @param {float} [ratio=1] - What ratio to keep between the width and height
* @param {integer} [minLimit=0] - Only square the element when the viewport width is above this limit
*/
function squareThis (element, ratio, minLimit)
{
// First of all, let's square the element
square(ratio, minLimit);
// Now we'll add an event listener so it happens automatically
window.addEventListener('resize', function(event) {
square(ratio, minLimit);
});
// This is just an inner function to help us keep DRY
function square(ratio, minLimit)
{
if(typeof(ratio) === "undefined")
{
ratio = 1;
}
if(typeof(minLimit) === "undefined")
{
minLimit = 0;
}
var viewportWidth = window.innerWidth;
if(viewportWidth >= minLimit)
{
var newElementHeight = $(element).width() * ratio;
$(element).height(newElementHeight);
}
else
{
$(element).height('auto');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment