Identify screen size to load content asynchronously

Asked

Viewed 782 times

2

I have a script that does reload every 10 seconds, loading a page into a div:

<script type="text/javascript">

    var tempo = 10000;
    function listar() {
        $.ajax({
            url:"lista.php",
            success: function (textStatus) {      
                $('#lista').html(textStatus);
            }
        }); 
    }

    function reload() {
        location.reload();
    }

    $(function() {  
        listar();
        setInterval(listar, tempo);
        setInterval(reload, 1800000);
    });

</script>

I would like that script, recognizes the type/size of screen (monitor, mobile phone, etc.) and load the file for the size.

Example:

When the screen is one monitor: carry php list.

When the screen is one cellular: carry lista_cel.php

1 answer

5


You could capture the screen size and with it make the condition to check the screen size and tell which php file will be called.

Adding the following code will take the window dimensions:

var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;

Changing the function listar() for listar(arquivo), to receive the file that will be called:

function listar(arquivo) {
    $.ajax({
        url: arquivo,
        success: function (textStatus) {      
            $('#lista').html(textStatus);
        }
    }); 
}

Finally, it uses the windowwidth variable to receive the width of the screen and makes the conditions by checking the width and setting which file will be called.

$(function() {
    var arquivo = "lista.php";

    var windowWidth = window.innerWidth;

    if (windowWidth < 1000 && windowWidth >= 400)
        arquivo = "lista_tablet.php";
    else
    if (windowWidth < 400)
        arquivo = "lista_cel.php";

    listar(arquivo);
    setInterval(listar(arquivo), tempo);
    setInterval(reload, 1800000);
});
  • Thiago, I got to test it now dude. So I did like I said, but Reload is crashing the page. From what I’ve seen, he’s been reloading the entire page over and over again. It seems to loop bigger and bigger. Before changing, it only loaded the "list.php". It’s working, but it is with this loop that grows more and more.

  • I played the IF inside the function listar() and it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.