how to only load one IFRAME using @media and display:none; CSS
Tags: javascript,css,iframe,media,hidden
Problem :
I am using @media CSS to serve up 3 different sizes pages depending on device viewport width.
I use 3 's so depending on screen width I hide 2 and display 1
the problem is that when I use 's it loads all 3 even when the iframe is within display:none;
I need only one of the 's to load mainly the one in the that is visible not the other two that are hidden.
here is an example of the html
<div class='s1'>
<p>Full size page content here</p>
<iframe id='frame1' src="chat/flashchat.php" width="513" height="500"> </iframe>
<p> more full size page content here</p>
</div>
<div class='s2'>
<p>Medium size page content here</p>
<iframe id='frame1' src="chat/flashchat.php" width="513" height="500"> </iframe>
<p>More medium content here</p>
</div>
<div class='s3'>
<p>Small page content here</p>
<iframe id='frame1' src="chat/flashchat.php" width="320" height="500"> </iframe>
<p>More small page content here</p>
</div>
here is the CSS:
@media handheld, screen and (min-width: 768px) {
.s2 {
display: none;
}
.s3 {
display: none;
}
.s1 {
display: block;
}
}
@media handheld, screen and (max-width:767px) and (min-width:513px) {
.s1 {
display: none;
}
.s3 {
display: none;
}
.s2 {
display: block;
}
}
@media handheld, screen and (max-width:512px) {
.s1 {
display: none;
}
.s2 {
display: none;
}
.s3 {
display: block;
}
}
I am thinking javascript might provide a solution but would like to avoid that method if possible. I can only allow one of these IFRAMES to load even though only one is displayed the 3 loading messes up an automatic login feature because the is actually loading 3 times even though it is hidden.
Any advise on resolving this issue?
Solution :
Here's the JS I used:
$(document).on('ready', responsiveVideo);
$(window).on('resize', responsiveVideo);
function responsiveVideo() {
var windowWidth = $(window).width();
// Let's make sure that the appropriate video is visible
$('.video-class-selector').each(function() {
if ($(this).hasClass('.js__video-hack')) {
return;
}
var isResponsiveVideo = $(this).parent('.video_mobile_wrapped').length,
BREAKPOINT = 768;
// Replace visible iframes with a proper iframe with a valid src attribute
var $original = $(this).find('iframe');
if ((isResponsiveVideo && windowWidth < BREAKPOINT) || (!isResponsiveVideo && windowWidth >= BREAKPOINT)) {
var $clone = $original.clone();
$clone.attr('src', $clone.attr('data-src'));
$original.replaceWith($clone);
$(this).addClass('js__video-hack');
}
});
}
My markup for the iframe looks like this:
<div class="video-class-selector">
<iframe data-src="..." ...></iframe>
</div>
The responsive one is wrapped in a div with class video_mobile_wrapped:
<div class='video_mobile_wrapped'>
<div class="video-class-selector">
<iframe data-src="..." ...></iframe>
</div>
</div>