-2

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 ?

NTor
  • 3
  • 2
  • 1
    Is the Javascript being applied from outside of the iFrame? If so, it will not work. – Jody Heavener Sep 16 '16 at 20:52
  • Does the script load in the page when it is rendered inside an iFrame? – Geeky Guy Sep 16 '16 at 20:52
  • This problem is not well detailed nd is confusing what you are asking. In addition all you have provided is a snippet of code and not a [mcve] – charlietfl Sep 16 '16 at 20:53
  • Also please avoid using iFrames for page layouts. See http://stackoverflow.com/questions/755795/are-iframes-html-obsolete – Geeky Guy Sep 16 '16 at 20:53
  • @JodyHeavener no, the javascript is from the page inside the iframe – NTor Sep 16 '16 at 21:01
  • @Renan it does. THe problem seems to be that the class only is added when there is a resize event. If the window already loads with a fixed width nothing happens. – NTor Sep 16 '16 at 21:11
  • Confirmed it works whenever I am trying to resize the width but not when the window is loaded with a fixed width. – NTor Sep 16 '16 at 21:16
  • @charlietfl I have added the full code snippet, it should be more clear now ! THe issue is related to the conditions set only working on resize events, not when the window is loaded with a fixed width. – NTor Sep 16 '16 at 21:21

1 Answers1

1

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
charlietfl
  • 170,828
  • 13
  • 121
  • 150