Autoplay video only working on resize action

This is my first post here. I searched here and found some useful code for an external .js file, that nearly works 100% in loading an image instead of video if the screen = <1024:

$(document).ready(function() {

$(window).resize(function(){
            var width = $("body").width();
            if(width <= 1024){
                $("#media_div").html("<img src='/img/benhat1280.jpg' />");
            }else{
                $("#media_div").html('<video src="/img/CT_HQ.mp4" autoplay mute loop />');
                $("#media_div img").css("height","auto");
                $("#media_div").fadeIn(2000);
            }
        })
      });

However, if >1024, it will only load the video if you being to resize the browser window. Also, the .fadein function is not working.

Best,
Benjamin

Just put your resize code into a function, call it when there is a resize and call it at start up. Also add opacity to 0 before you fadein.

$(document).ready(function() {

        function onResize(){
            var width = $("body").width();
            if(width <= 1024){
                $("#media_div").html("<img src='/img/benhat1280.jpg' />");
            }else{          
                $("#media_div").html('<video src="/img/CT_HQ.mp4" autoplay mute loop />');
                $("#media_div img").css("height","auto");
                $("#media_div").css('opacity', 0);
                $("#media_div").fadeIn(2000);
            }
        }

        $(window).resize(function(){
             onResize();
        };

        onResize();
     });