Nadir Nadir - 4 months ago 12
jQuery Question

jQuery keyup event handler doesn't run in real time

I would like to change dynamically the width and height which are mentionned in the iframe, so in the textarea. To do this, I use two input text and try to recover values in real time. Also, I would like to keep ratio when the value of the width or the height is changing.


<form id="generation_lien" action="/">
<textarea id="embed_code" readonly="readonly"></textarea>
<label>Size :</label>
<input id="width_iframe" type="text" value="640" />
<input id="height_iframe" type="text" value="360" />


function calculateFrameWidth(){return $('#width_iframe').val();}
function calculateFrameHeight(){return $('#height_iframe').val();}
widthIframe = calculateFrameWidth();
/*heightIframe = widthIframe / 1.77777778;*/
heightIframe = calculateFrameHeight();
/*widthIframe = heightIframe * 1.77777778;*/
var widthIframe = calculateFrameWidth();
var heightIframe = calculateFrameHeight();
document.getElementById('embed_code').innerHTML = '<iframe id="iframe_link" src="mysite/iframe.php" width="'+widthIframe+'" height="'+heightIframe+'></iframe>';


You can calculate ratio of size by Width / Height.

var firstWidth = $("#width_iframe").val();
var firstHeight = $("#height_iframe").val();
var ratio = firstWidth / firstHeight;
setSize(firstWidth, firstHeight);

$("#width_iframe").on("keyup change", function(){
    var width = $(this).val();
    $("#height_iframe").val(width / ratio);
    setSize(width, $("#height_iframe").val());

$("#height_iframe").on("keyup change", function(){
    var height = $(this).val();
    $("#width_iframe").val(height * ratio);
    setSize($("#width_iframe").val(), height);

function setSize(widthIframe, heightIframe){
    $("#embed_code").text('<iframe id="iframe_link" src="mysite/iframe.php" width="'+widthIframe+'" height="'+heightIframe+'"></iframe>');
<script src=""></script>
<textarea id="embed_code" readonly="readonly" style="width:100%"></textarea>
<label>Size :</label>
<input id="width_iframe" type="text" value="640" />
<input id="height_iframe" type="text" value="360" />