Get/Set/Keep The Ratio Aspect Of An Element - jQuery KeepRatio

Get/Set/Keep The Ratio Aspect Of An Element - jQuery KeepRatio
File Size: 3.97 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

The jQuery KeepRatio library provides 3 methods to set, get, and keep the aspect ratio of a DOM element.

Great for responsive design that keeps your element with the same aspect ratio on different screens.

How to use it:

1. Insert the JavaScript file keep-ratio.js after jQuery.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous">
</script>
<script src="js/keep-ratio.js"></script>

2. Set the aspect ratio.

<div class="box">
  ... content ...
</div>
var $els = $( ".box" );

// 1:1
$els.ratio( 1 );

3. Keep the current aspect ratio.

var $els = $( ".box" );
$els.keepRatio();

4. Outpu the aspect ratio in the console.

var $els = $( ".box" );
console.log( "keepRatio", $els );

5. Restore the aspect ratio.

$els.freeRatio( true )

6. You can also set the aspect ratio in the data attribute:

<div class="box"
     data-keep-ratio=1>
</div>
$.keepRatio.register()

This awesome jQuery plugin is developed by Cygraph. For more Advanced Usages, please check the demo page or visit the official website.