Looking for a jQuery/JS solution for making a Youtube video responsive

Hi,

Looking for a solution to make a Youtube video iframe responsive I found this page:

Fluid Width Video

Now I’m trying for hours to apply it on my code example here:

Trying to make it responsive

but it’s not working and I don’t understand why.

Could you please help me with this? I’m not looking for a CSS solution. I’m looking for a jQuery/JS solution.

Thanks

I’ve often used this code with success. You just have to remember to give the containing div a class of video-container.

// Make videos responsive
	var $allVideos = $("iframe[src^='//player.vimeo.com'], iframe[src^='https://www.youtube.com'], iframe[src^='http://www.youtube.com'], object, embed"),
	$fluidEl = $(".video-container");
	
	$allVideos.each(function() {
		
		$(this)
			// jQuery .data does not work on object/embed elements
			.attr('data-aspectRatio', this.height / this.width)
			.removeAttr('height')
			.removeAttr('width');
			
		});
	
		$(window).resize(function() {
			
			var newWidth = $fluidEl.width();
			
			$allVideos.each(function() {
				
				var $el = $(this);
				$el
					.width(newWidth)
					.height(newWidth * $el.attr('data-aspectRatio'));
			});
			
		}).resize();
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.