Home > other >  Why this code is looping into same page ? I want to seperate design for desktop and mobile view. How
Why this code is looping into same page ? I want to seperate design for desktop and mobile view. How

Time:06-20

<script>
var window_width = jQuery(window).width();
var device_layout;
    if(window_width >= 992){
        device_layout = "desktop";
    }
    if(window_width >= 768 && window_width <= 991){
        device_layout = "tablet";
    }
    if(window_width <= 767){
        device_layout = "mobile";
    }
    
    window.location = "products.php?device=" device_layout;
        </script>

How to resolve it ? Any mistakes in my code ? Why this code is looping into same page ? I want to seperate design for desktop and mobile view. How can i resolve it in html page ? Thanks in advance.

CodePudding user response:

This code causes an infinite loop because you don't do any check to see if the query string is different than the one calculated based off the width of the screen.

You can use the URLSearchParams class to get the query parameters then do a check based on that.

<script>
    var window_width = jQuery(window).width();
    var device_layout;
    var script_name = 'index.php';

    var url_params = new URLSearchParams(window.location.search);
    var layout_param = url_params.get('device');

    if(window_width >= 992){
        device_layout = "desktop";
    }
    if(window_width >= 768 && window_width <= 991){
        device_layout = "tablet";
    }
    if(window_width <= 767){
        device_layout = "mobile";
    }

    if (layout_param !== device_layout) {
        window.location = script_name   "?device=" device_layout;
    }
</script>
  • Related