body {
font-family: Arial;
}
div {
margin: 20px;
background: yellow;
width: 50px;
height: 100px;
}
JavaScript
(function( $ ) {
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
// If not, output an error message
throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
$.cssHooks[ "square" ] = {
get: function( elem, computed, extra ) {
return $(elem).width();
},
set: function( elem, value ) {
value = value.slice(0, -2);
$(elem).css('width', value);
$(elem).css('height', value);
}
};
$.fx.step.square = function( fx ) {
var w = fx.elem.clientWidth;
var h = fx.elem.clientHeight;
// If not square and first time started animation
if (fx.now == fx.start && (w - h) > 2 || (w - h ) < -2 ) {
$("div").stop().animate({'width': fx.end, 'height': fx.end}, fx.options.duration);
}
if ( (w - h) > 2 || (w - h ) < -2 ) {
return;
}
else {
$.cssHooks.square.set( fx.elem, fx.now + fx.unit );
}
};
$(".click").click(function(){
var w = $('div').width();
var h = $('div').height();
if (h == w) {
a = w * 2;
}
else
var a = w > h ? w : h;
$("div").animate({'square': a}, 1000);
});
$(".random").click(function(){
var side = $(window).width() < $(window).height() ? $(window).width() : $(window).height();
var limiter = side/3;
var h = Math.floor(Math.random()*limiter);
var w = Math.floor(Math.random()*limiter);
$("div").animate({'width': w, 'height': h}, 1000);
});
});
})( jQuery );
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.