I'm working on a responsive page whereby there's a embeded video content.
How can I update the parameter width/height in the iframe src as well as the iframe attribute width/height based on the width of the parent container as well as change when the window/orientation changes?
My mark-up:
<div class="content">
<div class="video">
<iframe src="http://www.foo.com/embeddedPlayer?id=4062930&width=672&height=377&autoPlay=false" width="672" height="377" border="0" frameborder="0" scrolling="no"></iframe>
</div>
</div>
Heres my JS:
var articleBodyWidth = $('.content').width(),
videoUrl = $('.video'),
videoSrc = videoUrl.find('iframe').attr('src'),
iframeWidth = videoUrl.find('iframe').attr('width'),
iframeHeight = videoUrl.find('iframe').attr('height');
// function to get param in url
function getParam(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(videoSrc);
if(results == null) {
return "";
} else {
return results[1];
}
}
var newWidth = articleBodyWidth,
newHeight = Math.round( (iframeHeight / iframeWidth) * articleBodyWidth );
// update iframe width and height
videoUrl.find('iframe').attr({
width: newWidth,
height: newHeight
});
I think this should do
$('.video iframe').attr('src', 'http://www.foo.com/embeddedPlayer?id=4062930&width=' + newWidth+ ' &height=' + newHeight + ' &autoPlay=false').css({
width: newWidth,
height: newHeight
})
Another solution is to use regex to replace height and width in the src
function updateVideo() {
var src = $('.video iframe').attr('src');
src = src.replace(/&width=\d+&/, '&width=' + newWidth + '&');
src = src.replace(/&height=\d+&/, '&height=' + newHeight + '&');
$('.video iframe').attr('src', src).attr({
width: newWidth,
height: newHeight
});
}
$(window).on('resize', updateVideo)