Add Poster with Text to Embedded YouTube Video

This is a continued modification of my earlier post for toggling multiple embedded YouTube videos into a larger playing div.

Since I was already using Posts to embed the videos, enabling a Featured Image for a Poster, and using the Content editor for a text overlay was a simple feat to accomplish.

Updated HTML:

<?php 
$args = array(
	'post_type' => 'post',
	'posts_per_page' => 1,
	'tax_query' => array(array(
		'taxonomy' => 'category',
		'terms' => $cat->slug,
		'field' => 'slug'
	))
);

$main_vid = get_posts($args);

foreach($main_vid as $post) : setup_postdata($post); ?>
		
	<div class="main_video_content">
		<?php if(has_post_thumbnail()) { ?>
			<div class="main_poster">
				<?php the_post_thumbnail(); ?>
				<div class="poster_content">
					<h2 class="title"><?php the_title(); ?></h2>
					<?php the_content(); ?>
				</div><!-- .poster_content -->
			</div><!-- .main_poster -->
		<?php } ?>
		<span class="embed-youtube"><?php the_field('video_embed_url'); ?></span>
	</div>
		
<?php endforeach; wp_reset_postdata(); ?>

New jQuery:

Fades the visibility of the poster and content, and plays the video.

jQuery('.main_video_content .embed-youtube iframe').attr( 'id', 'video');
	
	jQuery(document).ready(function() {
	  jQuery('.main_poster').on('click', function() {
	 
	    jQuery("#video")[0].src += "&autoplay=1";
	    //ev.preventDefault();		
		
		jQuery('.main_poster').fadeOut("slow");
	  });
	});

Update to Previous jQuery:

jQuery('#videos iframe').each(function(){
 
 
 var el = jQuery(this);
 
 var src = el.attr('src');
 var videoIDStart = src.indexOf('embed/');
 
 // add embed string length to start at right place
 videoIDStart +=6;
 var videoIDEnd = src.indexOf('?');

 
 var videoID = src.substr(videoIDStart, Number(videoIDEnd - videoIDStart));
 
 var videoImage = 'https://img.youtube.com/vi/'+videoID+'/0.jpg';
 
 var parentElement = el.closest('span.embed-youtube');
 
 parentElement.append('<img src="'+videoImage+'" class="newsroom-video-thumb"/>');
 parentElement.find('iframe').hide();
 
 parentElement.find('img.newsroom-video-thumb').on('click',function(){
 var newVideo = parentElement.find('iframe').clone();
 
 jQuery('.main_video').find('iframe').remove();
 jQuery('.main_poster').hide(); // add this line to hide the poster wrapper on click and play the video
 jQuery('.main_video').find('.embed-youtube').append(newVideo); 
 jQuery('.main_video').find('iframe').show();
 });
 
});

 

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.