Search code examples
javascriptjqueryonresize

Using .onresize to control text on responsive video player


I'm trying to control the size of the text used to show elapsed and total time of a video player. I am currently controlling the play/pause/sound and full screen icons, but can't access the time display. Below is the javascript used to resize the controls on window resize:

window.onload = function() {
resize();
}

window.onresize = function() {
resize();
}

function resize() {
    document.getElementsByClassName('play')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';
    document.getElementsByClassName('fullscreen')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';
    document.getElementsByClassName('mute')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';
    document.getElementsByClassName('time-played')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';
}

Also trying to figure out the best way to minimize and simplify this using jQuery(to consolidate all of the classes into one array, similar to:

$('.play .fullscreen .mute .time-played')

My current implementation: jsfiddle


Solution

  • If you'd like to use jQuery, then you can run the resize method on .ready() and add window .resize() bindings as well, like so:

    $(document).ready(function () {
        // resize on dom ready
        resizePlayer();
    
        // add window resize binding
        $(window).resize(resizePlayer);
    });
    

    To combine selectors in jQuery, you can do something like this:

    $('.play, .fullscreen, .mute, .time-played')
    

    So, your resize method can now look something like this:

    function resizePlayer() {
        // Set your width to whatever you want...
        // this is just a rough translation of your method above
        var newWidth = $('.timeline').outerHeight() * 0.25;
    
        $('.play, .fullscreen, .mute, .time-played').width(newWidth);
    }