Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically detect browser viewport change in size?

I've been having problems with scaling... automatic... dynamic... adaptive.... etc...

I have seen websites where as you make the window smaller eg. grab a corner and make the window smaller, fonts get bigger, things move around...

I've got the moving part, I don't know how to dynamically detect the browser viewport... is that a refreshing thing or?...

As you can see here, these motion things that I've used only work upon screen refresh, in particular I have a tablet, and if I visit the page in landscape, it doesn't apply; if I rotate it and then refresh, it applies.

<script language="JavaScript" type="text/javascript">
var x = screen.width;
var y = screen.height;
function scale() {
var z = x/y;
    if (z<1) {
     document.getElementById('header').style.width = "100%";
     document.getElementById('menu').style.marginLeft = "0";
     document.getElementById('menu').style.width = "20%";
     document.getElementById('menu2').style.width = "30%";
     document.getElementById('menu3').style.width = "20%";
     document.getElementById('menu4').style.width = "20%";
     document.getElementById('properties').style.width = "30%";
     document.getElementById('properties').style.marginLeft = "35%";
    }
}
scale();
</script>

This is code provided by someone from Stack Overflow regarding font, I imagine it may be similar to the direction I'm going

$( window ).resize(function() {
    $( "#container" ).css("font-size",function() {
        var value = $( "#container" ).css("width");
        console.log(parseInt(value)/24 + "pt");
        return parseInt(value)/24 + "pt";
    }) ;
});

What part is dynamic?

This console.log, I haven't used that before

Any help would be greatly appreciatedd

like image 222
pearlescentcrescent Avatar asked Feb 24 '15 15:02

pearlescentcrescent


1 Answers

After reading your question and comments, I'm still a little confused, but maybe this will help.

First off, learn to use Chrome's Dev Tools. They are awesome! The most important thing you need to know for now is this:

To use console.log:

  1. In your JavaScript, write a line like console.log('Hello World!');
  2. Open that page in Google Chrome
  3. Press F12 To Toggle (Open/Close) the DevTools
  4. It will probably be on the Resources tab, this is a good place to check all your resources are loaded, but not what you're looking for.
  5. Click on the tab labeled Console
  6. Viola! You should see Hello World! if that line of JS has run.
  7. Welcome to awesomsauce!

Now as to an easier visual for resize testing, try the following jQuery enhanced JavaScript: (commented for explanations, remove comments if you please)

//  This first line is the same as JavaScript's `document.ready = function() {}
//  This simply starts your code running as soon as the document is loaded and ready to go
//  It's safe to use in <head> or in <body> and will always ensure your JS is running with the page load
$(function() {
    //  Here I use .on instead of direct reference to the event as this is just good practice4 with jQuery
    //  You'll later learn you can use this with prewritten methods to "turn on/off" methods asigned to specific events
    $(window).on('resize', function(e) {
        //  Little JS Tip, No need to write `var` 50thousand times. Just use a comma and write your new variable
        var x = $(this).width(),    //  variable for window width assigned to `x`
            y = $(this).height(),   //  variable for window height assigned to `y`
            z = x/y,    //  your conversion you were using in the code you have in your question, there's plenty of different ways to test for size changes, do some Googling on "aspect ratio" as it's usually best way to go
            //  this next line is a little complicated
            //  It's assigning a variable based on result of an `inline if statement`
            //  What it says: if (element with id 'myOutput' exist) then assign that element and empty it of all it's HTML, else build the element using jQuery's element object method and append it to the <body>
            //  jQuery's element object building is easy, just remember it like this: jQuery("<tagName />", { object of attributes })
            output = $('#myOutput').length ? $('#myOutput').empty() : $('<div />', { id: 'myOutput', style: 'background: #ffa; padding: 10px; position: fixed; right: 30px; top: 30px; z-index: 999;' }).appendTo('body'),
            //  the following lines build the inner HTML for showing the results of our window dimensions
            pX = $('<p />', { text: 'x: '+x }).appendTo(output),
            pY = $('<p />', { text: 'y: '+y }).appendTo(output),
            pZ = $('<p />', { text: 'z: '+z.toFixed(5) }).appendTo(output);
    });
})

If you're using Google Chrome right now, then you can test this right now! Simply press F12 and click on Console tab. Copy the minimized code below and then click in the Console. You should see a blinking cursor ready for input. Paste the code and press enter! Then just resize the window and watch upper right! *notein upper most right you will probably see Chrome's own size box. Mine has a yellow background

Minified Code:

$(function(){$(window).on("resize",function(a){a=$(this).width();var c=$(this).height(),d=a/c,b=$("#myOutput").length?$("#myOutput").empty():$("<div />",{id:"myOutput",style:"background: #ffa; padding: 10px; position: fixed; right: 30px; top: 30px; z-index: 999;"}).appendTo("body");$("<p />",{text:"x: "+a}).appendTo(b);$("<p />",{text:"y: "+c}).appendTo(b);$("<p />",{text:"z: "+d.toFixed(5)}).appendTo(b)})});
like image 177
SpYk3HH Avatar answered Oct 13 '22 09:10

SpYk3HH