Search code examples
jqueryjcrop

I calculate an aspect ratio, but it should be updated when old value changes


I am using jCrop and I need a set aspect ratio. For example, if someone enters "2" to X textbox and "2" to Y textbox, the aspect ratio should be 1.

However, if I change the values on textboxes (e.g to 3 and 1), jCrop should obtain the new values. Right now it only initializes, and doesn't look back.

The code is the following. (I tried alot more but couldn't figure it out.)

-JQUERY-
jQuery(function($){
   var numberX = $('#numberX').val();
   var numberY = $('#numberY').val();

   $('#jcrop_target').Jcrop({
      aspectRatio: ($(this).numberX / $(this).numberY),
   ... rest of the codes

-HTML-
<input type="text" id="numberX" name="numberX" value=""/>
<input type="text" id="numberY" name="numberY" value="" />

TLDR; When I change values of numberX and numberY textboxes, it should reflect to jCrop. jCrop only keeps the init values. When values on textboxes change, aspect ratio should be re-calculated.

Any help would be greatly appreciated!


Solution

  • Make your code into a function(). Then with jQuery you can run the function on document.ready and on change (See http://api.jquery.com/change/)

    For example,

    function changenumbers(){
       var numberX = $('#numberX').val();
       var numberY = $('#numberY').val();
    
       $('#jcrop_target').Jcrop({
          aspectRatio: ($(this).numberX / $(this).numberY),
       /* ... rest of the code */
    }
    $document.ready(function(){
       changenumbers();
       $("#numberX").change(function(){ changenumbers(); }
       $("#numberY").change(function(){ changenumbers(); }
    }