Email
Email

Reputation: 2425

Changing jquery (plugin) options on-the-fly

Imagine you use a plugin and want to change settings on-the-fly, there are 2 options to achieve this if the plugin has not built-in options request:

  1. You modify the plugin to handle options in a request

  2. You try to modify the javascript onrequest.

It's a general subject but let's take this simple image cropping plugin as an example: http://deepliquid.com/projects/Jcrop/

If I want to change the aspect ratio onclick on a link.

Onpage-load settings:

<script>
    jQuery(function($){
      $('#target').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 2/3
      }
</script>

Change settings onclick to

<script>
    jQuery(function($){
      $('#target').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 1/2
      }})
</script>

I now wonder if jquery or javascript would be able, following the 2. approach, to kill the first javascript (like it could be easily done with a div) and replace it with the second javascript. I already tried by providing a script name-tag to identify but without success. wrapping javascript in a div seems not to be w3-compliant. Does anyone have an idea about how to achieve this?

Maybe someone would share also a step-by-step tut to easily modify a plugin to take additonal options in a request similar like so:

<div class="target {aspectRatio:1/2}

Upvotes: 0

Views: 1665

Answers (2)

Yulia Gurova
Yulia Gurova

Reputation: 108

For Jcrop:

jQuery(function($){
  $('#my_jcrop').Jcrop({
    onChange: updatePreview,
    onSelect: updatePreview,
    aspectRatio: old_aspectRatio
  }};

I changed the aspectRatio of such way

$('#my_jcrop').Jcrop({aspectRatio: new_aspectRatio['x']/new_aspectRatio['y']});

and for function updatePreview

function updatePreview(c)
   {
 if (c.w!=0 && c.h!=0){ 
    coord = c;
 }
    if (parseInt(c.w) > 0)
    {
      var rx = preview_size['x']/c.w;
      var ry = preview_size['y']/c.h;

   preview.width = Math.round(rx * boundx) + 'px';
      preview.height = Math.round(ry * boundy) + 'px';
      preview.marginLeft = '-' + Math.round(rx * c.x) + 'px';
      preview.marginTop = '-' + Math.round(ry * c.y) + 'px';

      $('#preview').css({
        width: preview.width,
        height: preview.height,
        marginLeft: preview.marginLeft,
        marginTop: preview.marginTop
      });
    }
  };

I changed the value of preview_size['x'] and preview_size['y']:

preview_size['x'] = new_aspectRatio['x'];
preview_size['y'] = new_aspectRatio['y'];

So if the new picture size 200x400px, then aspectRatio will be 200/400 = 1/2

Upvotes: 1

Charlotte Dann
Charlotte Dann

Reputation: 298

try using data attributes - <div class="target" data-aspect-ratio="1/2">

 $('.target').Jcrop({
    onChange: updatePreview,
    onSelect: updatePreview,
    aspectRatio: $(this).attr('data-aspect-ratio')
  }

Upvotes: 0

Related Questions