YUI 3.x Home -

YUI Library Examples: Resize: Simple Resize with Constrain Plugin

Resize: Simple Resize with Constrain Plugin

This example shows how to create a resizable element where the resize operation is constrained to a specific aspect ratio.

Resize Me

Setting up the Node

First we need to create an HTML element to make resizable.

  1. <div id="demo">Resize Me</div>
<div id="demo">Resize Me</div>

Next, we'll give that element some CSS to make it visible.

  1. #demo {
  2. height: 100px;
  3. width: 100px;
  4. border: 1px solid black;
  5. background-color: #8DD5E7;
  6. cursor: move;
  7. position: relative;
  8. }
#demo {
    height: 100px;
    width: 100px;
    border: 1px solid black;
    background-color: #8DD5E7;
    cursor: move;
    position: relative;
}

Setting up the YUI Instance

Now we need to create our YUI instance and tell it to load the resize module. This module is a rollup that includes the resize-constrain submodule; that means we have access to the ResizeConstrained plugin.

  1. YUI().use('resize');
YUI().use('resize');

Making the Node resizable

Now that we have a YUI instance with the resize module, we need to instantiate the Resize instance on this Node.

  1. YUI().use('resize', function(Y) {
  2.  
  3. var resize = new Y.Resize({
  4. //Selector of the node to resize
  5. node: '#demo'
  6. });
  7.  
  8. });
YUI().use('resize', function(Y) {
 
    var resize = new Y.Resize({
        //Selector of the node to resize
        node: '#demo'
    });
 
});

Adding the Constrained Plugin

Now we will plug ResizeConstrained into our Resize instance. This plugin will allow you to limit the resize dimensions in special ways.

  1. YUI().use('resize', function(Y) {
  2.  
  3. var resize = new Y.Resize({
  4. //Selector of the node to resize
  5. node: '#demo'
  6. });
  7. resize.plug(Y.Plugin.ResizeConstrained, {
  8. minWidth: 50,
  9. minHeight: 50,
  10. maxWidth: 300,
  11. maxHeight: 300,
  12. preserveRatio: true
  13. });
  14.  
  15. });
YUI().use('resize', function(Y) {
 
    var resize = new Y.Resize({
        //Selector of the node to resize
        node: '#demo'
    });
    resize.plug(Y.Plugin.ResizeConstrained, {
	    minWidth: 50,
	    minHeight: 50,
	    maxWidth: 300,
	    maxHeight: 300,
	    preserveRatio: true
    });
 
});

In this case, we've used the constraint feature to specify minimum height and width for the element while setting preserveRatio to true, locking in the original aspect ratio for the element.

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings