James Harold James Harold - 1 month ago 5
Javascript Question

How to load the embeded video only after some click-event was triggered. jQuery

What I have now satisfies me in terms of an overall effect: Click on "show me", it displays an YT Video, when clicked once again - vid will hide etc. BUT even when site is loaded in the first place (and YT video is hidden) - all of its (Mb) size is counted as it was displayed causing the website to load slowly. My question is how to load the embeded video (with its size) only after I clicked on "Show me" element.

This is what I have:


HTML:

<div class="#">
<span class="#" id="show_me"><i class="icon fa-angle-down"></i>Show Me</span>
<span class="#" id="shown">
<iframe width="100%" height="315" src="https://www.youtube.com/embed/#" frameborder="0" allowfullscreen></iframe>
</span>
</div>


JS:

$(document).ready(function(){
$("#show_me").click(function(){
$("#shown").toggle();
});
});


CSS:

#shown {
display: none;
}

Answer

Try something like this:

HTML:

<div class="#">
    <a href="#" id="show_me"><i class="icon fa-angle-down"></i>Show Me</a>
    <div id="i_frame"></div>
</div>

JS:

$(document).ready(function(){
    $("#show_me").click(function(e){

        e.preventDefault();

        if ($(this).is(".opened") ) {
            $(this).removeClass('opened');
            $("#i_frame").hide().html('');

        } else {
            $(this).addClass('opened');
            $("#i_frame").show().html("<iframe width='100%' height='315' src='https://www.youtube.com/embed/#' frameborder='0' allowfullscreen></iframe>");
        }

    });
});

CSS:

#i_frame {
    display: none;
}
Comments