Is it possible to set/update jCrop aspect ratio on select box change?

javascript, jcrop, jquery, select

Solution

You can set the Aspect Ratio by:

 jcrop_api.setOptions({
    aspectRatio: yourAspectRatioValue
 }); 

In your code,

$("#ratio").change(function () {
        var text = $(this).find(':selected').text();
        ratio = text;
        val = $(this).val();
        selection = '[0,0,' + val + ']';
        jcrop_api.setOptions({
        aspectRatio: ratio
        }); 
  }).trigger('change');

But place this code after the code where you are applying jCrop on the image.

Problem

Is it possible to set/update jCrop aspect ratio on select box change? I've added a ratio and selection variables and worked fine statically but can't get it to work on select change while the select alerts the right values ``` jQuery(function ($) { var ratio = 4 / 3 var selection = '[0,0,4,3]'; $("#ratio").change(function () { var text = $(this).find(':selected').text(); ratio = text; val = $(this).val(); selection = '[0,0,' + val + ']'; alert(ratio) }).trigger('change'); // Create variables (in this scope) to hold the API and image size var jcrop_api, boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); console.log('init', [xsize, ysize]); $('#target').Jcrop({ onChange: updatePreview, onSelect: updateCoords, setSelect: selection, aspectRatio: ratio }, function () { // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); $('#coords').on('change', 'input', function (e) { var x1 = $('#X').val(), y1 = $('#Y').val(); jcrop_api.setSelect([x, y]); }); function updatePreview(c) { if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $pimg.css({ width: Math.round(rx * boundx) + 'px', height: Math.round(ry * boundy) + 'px', marginLeft: '-' + Math.round(rx * c.x) + 'px', marginTop: '-' + Math.round(ry * c.y) + 'px' }); } }; }); function updateCoords(c) { $('#X').val(Math.round(c.x)); $('#Y').val(Math.round(c.y)); $('#W').val(Math.round(c.w)); $('#H').val(Math.round(c.h)); }; ``` And here is the select values and text which I'm not stick to: ``` <select id="ratio"> <option value="4,3">1.3</option> <option value="6,3">1.6</option> <option value="9,3">.8</option> </select> ```

Original source