Oliver Prenzel
Oliver Prenzel

Reputation: 31

Determine viewport size with jQuery

I am trying to determine the viewport size through jQuery. Unfortunately I do not get the results I am trying for.

First off my css:

.site {
    max-width: 960px;
}

@media only screen and (min-width : 760px) and (max-width : 1040px)  /* tablet */{
.site {
    max-width: 620px;
}

@media only screen and (min-width : 240px) and (max-width : 759px) /* mobile */{
.site {
    max-width: 285px;
}

Now I have been trying two different versions of determining the viewport size:

$(window).ready(function() {
    var viewport = $('.site').css("width");
});
$(function() {
    if ( viewport <= '285px' ) {
        console.log( "Mobile,", viewport ) ;}
    else if ( viewport <= '620px' ) {
        console.log( "Tablet,", viewport ) ;}
    else {
        console.log( "Desktop,", viewport ) };
});

This unfortunately always returns "Mobile, 285px", no matter what size ".site" is... It does not help changing ".css("width")" to ".css(width)" or ".width()" either.

The second version I have tried was:

$(window).ready(function() {
    var viewport = $(window).width();
});
$(function() {
    if ( viewport <= 759 ) {
        console.log( "Mobile,", viewport ) ;}
    else if ( viewport <= 1040 ) {
        console.log( "Tablet,", viewport ) ;}
    else {
        console.log( "Desktop,", viewport ) };
});

This will always return an error in the console:

Uncaught ReferenceError: viewport is not defined 
(anonymous function) 
j 
k.fireWith 
n.extend.ready 
I

It doesn't help changing "$(window)" to "$('.site')" either.

What am I doing wrong?

( For further explanation: My ultimate goal is resizing the negative margin I give to an off canvas navigation to better fit the screen width. And yes, I am at a mere beginners level with jQuery.)

Upvotes: 1

Views: 3131

Answers (1)

David Jones
David Jones

Reputation: 4305

Try this:

$(window).ready(function() {
    var viewport = $(window).width();

    if ( viewport <= 759 ) {
        console.log( "Mobile,", viewport ) ;}
    else if ( viewport <= 1040 ) {
        console.log( "Tablet,", viewport ) ;}
    else {
        console.log( "Desktop,", viewport ) };
});

There is no need for the second function. You might as well do everything in your window ready block.

Here is a fiddle

NOTE: In the fiddle it will be getting the width of the result section so it will produce smaller results than the screen width. Make the result section wider to see the width value change.

Upvotes: 1

Related Questions