Blog

Using the .click() jQuery Method to Hide a Link when Clicked and then Display an Autoplay YouTube Video
Posted on February 19, 2014 in jQuery by Matt Jennings

CSS and HTML

Somewhere in your website include a script tag that points to latest Google jQuery API.

Note: In some cases if you use an older jQuery library this code will not work, especially in IE! Also, jQuery in this post has been tested and does work in IE7+ but for some reason the JSFiddle link doesn’t work in IE.

The code below displays an anchor tag and hides a YouTube iframe.

<style type="text/css">
.hide
{
    display: none;
}
</style>

<div id="video-wrapper">

    <a class="click-play-video" href="#">Click to play video</a>

    <iframe class="youtube-video hide" width="560" height="315" src="//www.youtube.com/embed/DxBiqyyjelM?autoplay=1" frameborder="0" allowfullscreen></iframe>

</div><!-- #video-wrapper -->

jQuery

First, don’t forget to wrap your jQuery in the jQuery Ready Event.

The code below uses the .click() jQuery method to attach an event handler to the
#video-wrapper selector.

When the .click-play-video anchor tag is clicked, the code inside the event handler adds the .hide class to that same anchor tag and removes the .hide class from the .youtube-video element so that the YouTube iframe is displayed.

The this keyword refers to the #video-wrapper selector. $("#video-wrapper") is the same as $(this) in the code below.

Finally, inside the YouTube iframe a ?autoplay=1 string is added at the end of the src attribute value to ensure the video starts playing immediately.

Here’s the JSFiddle. Enjoy!

$("#video-wrapper").click(function(){

    $(this).find(".click-play-video").addClass("hide");
    $(this).find(".youtube-video").removeClass("hide");    

});

Leave a Reply

To Top ↑