James Harold
James Harold

Reputation: 27

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;
}

Upvotes: 1

Views: 40

Answers (1)

jeremykenedy
jeremykenedy

Reputation: 4285

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");
            $(this).find(".icon").removeClass("fa-angle-up").addClass("fa-angle-down");
            $("#i_frame").hide().html("");

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

    });
});

CSS:

#i_frame {
    display: none;
}

https://jsfiddle.net/jeremykenedy/fkcnncjm/

Upvotes: 2

Related Questions