NTor NTor - 2 months ago 9
HTML Question

How to force resize inside iframe?

I have the following javascript code snippet for forcing a css class when the width is under 768:

<script>
$( document ).ready(function() {
var resizing = false;
function doResize() {
var w=$(window).innerWidth();
console.log(w);
if (w < 1320 && w > 768) {
$('input[name="start"]').val("Retry");
$('input[name="stop"]').val("Stop");
} else {
$('input[name="start"]').val("Retry command");
$('input[name="stop"]').val("Stop command");
}
if (w < 768 ) {
$('.div').addClass('mobile');
} else {
$('.div').removeClass('mobile') });
}
}

$(window).resize(function(e) {
if (resizing!==false) {
clearTimeout(resizing);
}
resizing=setTimeout(doResize, 200);
});
})
</script>


This works perfectly well when I am opening the page on a mobile device.

However, when I add the same page inside an iframe for a mobile app it stops working and assumes the width is higher than 768.

Edit : It seems there needs to be a resize event for the conditions to work. If I load the iframe with the page in a browser and resize it, everything works fine. If I load it with width < 768 it only adds the css class after I change window width.

What could be wrong and how could I fix this ?

Answer

I think all you need is to trigger resize right after the handler is set up, or call doresize()

$(window).resize(function(e) {
       if (resizing!==false) {
           clearTimeout(resizing);
       }
       resizing=setTimeout(doResize, 200);
}).resize();// trigger it on page load now