0

A few elements on a site im building take into account the size of the client. If the user decides to re size the window, some elements will look messed up. So, im trying to build a function that is constantly checking if any of dimensions change.

this is what ive made so far

<script>
    var initial_width = document.body.offsetWidth,
        initial_height = document.body.offsetHeight,
        timer = window.setInterval(function () {checksize()}, 10);

        function checksize () {
            var current_width = document.body.offsetWidth,
                current_height = document.body.offsetHeight;
                if((initial_width != current_width) || (initial_height != current_height)){
                    location.reload();
                } 
                else{
                    document.getElementById("test").innerHTML = "no change";
                }
        }   
</script>

it does work, sometimes, but if the window is re sized beyond a certain point it just keeps refreshing.

Any suggestions on how to fix / improve this code? or should i take a different approach?

Cheers.

Alex
  • 122
  • 9
  • 1
    You should take a different approach. Consider using a reactive layout (library, framework, etc.) Unrelated, but `function () { checksize() }` seems like a really roundabout way of saying `checksize`. – Dave Newton Sep 04 '14 at 17:31
  • Have you tried this? http://stackoverflow.com/questions/5489946/jquery-how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-ac – Richard A. Sep 04 '14 at 17:32
  • Are you able to use jQuery? If so you can use `$(window).on('resize', function() {...})`. http://api.jquery.com/resize/ – Tricky12 Sep 04 '14 at 17:33

1 Answers1

0

Wrap any code you wish to re-bind in this:

//declare global variable
var windowWidth = "";   

$(window).resize(function() {
    windowWidth = $(window).width();

    if (windowWidth < 768) {
        //change element size
    } else if (windowWidth >= 768 || windowWidth < 1000) {
        //change element size again
    } else {
        //change element size again
    }
});
Mike Legacy
  • 1,056
  • 1
  • 10
  • 24
  • Cheers! do you think i should replace the reload function to something that just re sizes the elements? i mean server wise, will it help with the bandwidth? – Alex Sep 04 '14 at 17:44
  • The issues isn't bandwidth, it's user experience, so yes, I would resize the elements and not reload the page. I will change my answer to show an example of how that would work.... – Mike Legacy Sep 04 '14 at 17:47
  • Answer updated to include how you would flag the different screen widths to change the content size. Obviously change the width values in the if statement to whatever you need them to be. You could do the same with the window height if you really wanted to. – Mike Legacy Sep 04 '14 at 17:51