javascripthtmliframemedia-queriesmediaquery

How to use Javascript media queries with window.addEventListener?


I am trying to use Javascipt media queries, but I can not get it work.

I am trying that iframe loads the frame only when size is less than 700px,:

<script>
mobile();
function mobile(){

    const mql = window.matchMedia('screen and (max-width: 700px)');

    checkMedia(mql);
    mql.addListener(checkMedia);

    function checkMedia(mql){

        if(mql.matches){

          function frameloading() {
              var frameone= document.getElementById("delayedframe");
              frameone.src = "360°-image url"
          };
          window.addEventListener("load",(frameloading));
        }
    }
}
</script>
<iframe id="delayedframe" src="about:blank" frameborder="0" style="position:absolute;top:100px;left:0px;right:0px;bottom:0px" height="200px" width="100%""><p>Your browser does not support iframes.</p></iframe>
I am used this post with this test: Multiple media queries in javascript

And I am also tried with:

<script>
function checkMediaQuery() {
  if (window.innerWidth > 700) {
    function frameloading() {
        var frameone= document.getElementById("delayedframe");
        frameone.src = "360°-image url"
    };
    window.addEventListener("load",(frameloading));
  }
}


window.addEventListener('resize', checkMediaQuery);
</script>
<iframe id="delayedframe" src="about:blank" frameborder="0" style="position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%" class="forcewide"><p>Your browser does not support iframes.</p></iframe>

Whole of those not loading the iframe when width is less than 700px.


Solution

  • I solved my problem by using this jQuery based code:

    $(document).ready(function()
    {
    if ($(window).width() <= 700)
         $('#IFRAMEID1').attr("src","url of the iframe");
    <iframe id="IFRAMEID1" src="about:blank" frameborder="0" style="position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"><p>Your browser does not support iframes.</p></iframe>

    I found template for this testing from here: https://stackoverflow.com/a/28795767/14276740