Search code examples
javascriptjqueryimagemathaspect-ratio

Keeping image ratio for its height using jQuery


Hey all i am trying to automatically get the height for an image. I can not seem to find any jQuery to do this?

What i am looking to do is something like it does in photoshop:

If the image was:

Width  = 778
Height = 346

And i want to change the width to 380 then typing in 380 into the Width textbox in photoshop changes the height to 169:

enter image description here

width  = 380
height = 169

How can i mimic this in Jquery?


Solution

  • How about something like this

    http://jsfiddle.net/Njf5k/1/
    

    HTML

    <label>Original Width</label>
    <input type="text" id="originalWidth" class="original" value="778" />
    <br />
    <label>Original Height</label>
    <input type="text" id="originalHeight" class="original" value="346" />
    <label>New Width</label>
    <input type="text" id="newWidth" class="new" />
    <br />
    <label>New Height</label>
    <input type="text" id="newHeight" class="new" />
    

    jQuery

    Its based on the fact that width/height remains a constant.

    $('#newWidth').keyup(function () {
        $('#newHeight').val(Math.round(
        ($('#originalHeight').val() * $('#newWidth').val()) / $('#originalWidth').val()));
    });