Phone: 406-788-9165

Javascript Tricks : Proper aspect mobile video embeds

Has there ever been a situation where you have a css element that doesn't properly scale with mobile responsive designs? For instance, embeded videos in an <iframe> or you have a slideshow designed for desktop.

Here is a simple javascript sniplet that can be used to give proper aspect to these elements:

Javascript

<script src="pathtojquery/jquery.1-9-1.min.js"></script> 
<script type="text/javascript">
$(document).ready(function(){
	$('iframe').css('width', getVideoWidth(500, 281, 10));
	$('iframe').css('height', getVideoHeight(500, 281, 10));
});

function getVideoHeight(width, height, padding) {
	var vheight = ($(window).width() - padding) * height / width;
	if (vheight > height) {
		vheight = height;
	}
	return vheight;
}
function getVideoWidth(width, height, padding) {
	var vwidth = $(window).width() - padding;
	if (vwidth > width) {
		vwidth = width;
	}
	return vwidth;	
}
</script>

CSS code for iframe Example

/*   Breakpoint at 510px for iframe video */
.container {
	padding: 5px;	
}
@media (max-width: 509px) {
	.container, .container iframe {
		width: 100%;
	}
}
@media (min-width: 510px) {
	.container {
		width: 500px; margin: 0 auto;
	}
	.container iframe {
		width: 500px; height: 281px;
	}
}

HTML iframe Example

<div class="container">
	<iframe src="https://player.vimeo.com/video/(videoId)" frameborder="0" webkitallowfullscreen 
	 mozallowfullscreen allowfullscreen></iframe>
</div>

getVideoWidth and getVideoHeight both take a maximum width, maximum height, and padding values. In our example, we are using 500px width by 281px height and 10px padding. When the viewport is less than the maximum width, the returned height value will be proper aspect to the device width.



Published by: Thomas Penwell
Initially published on: Feburary 13, 2016
Article last modified on: Saturday, February 13, 2016.

Home - Web Portfolio - Web site Tools - Database Design Service - Consulting
Web Design Service - Web Hosting Solutions - Service Rates
Client Login - Contact Us - Promotions - Partners - Articles - Perl Scripts


Our Sites:
restaurantorderpad.com