jqueryfunctioncalculatortimecodes

How can I change my textfield on input change calculated by a function?


This is my timecode calculator. When I change the input field value, then also the timecode should change.

var fps = 25;
var currentFrame =  $('.timecode_input').val();
var SS = Math.floor(currentFrame / fps);
var MM = Math.floor(SS / 60);
var HH = Math.floor(MM / 60);
var FF = currentFrame - (SS * fps);

function pad(str, width, what, left) {
    str = String(str);
    what = String(what);
    var w = width - str.length;

    if (left) {
        return (new Array(w + 1)).join(what) + str;
    } else {
        return str + (new Array(w + 1)).join(what);
    }
}

var i,
    timecode = [HH, MM, SS, FF];

for (i = 0; i < timecode.length; i += 1) {
    timecode[i] = pad(timecode[i], 2, 0, true);
}

var resultString = timecode.join(':'); // HH:MM:SS:FF

var timecode_p = document.querySelector('.timecode_output'),
    input = document.querySelector('.timecode_input');

function setText(v){
    timecode_p.innerHTML = resultString;
     console.log(resultString);
}

input.addEventListener('input', function(){ 
    setText( this.value );
    console.log(this.value );
})

setText(input.value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="timecode_input" type="text" value="25" style="width:90%"> Frames
<p class="timecode_output" style="margin-top:10px"></p>


Solution

  • All this code needs to be inside a function and get recalled on the event (maybe not the var definitions).

    That is because the event is only calling the setText method which updates the innerHTML property. It never actually changes your timecode variable.

    var fps = 25;
    var currentFrame =  $('.timecode_input').val();
    var SS = Math.floor(currentFrame / fps);
    var MM = Math.floor(SS / 60);
    var HH = Math.floor(MM / 60);
    var FF = currentFrame - (SS * fps);
    
    
    var i,
        timecode = [HH, MM, SS, FF];
    
    for (i = 0; i < timecode.length; i += 1) {
        timecode[i] = pad(timecode[i], 2, 0, true);
    }
    
    var resultString = timecode.join(':'); // HH:MM:SS:FF