Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  82] [ 1]  / answers: 1 / hits: 42079  / 12 Years ago, tue, july 3, 2012, 12:00:00

For a responsive template, I have a media query in my CSS:


@media screen and (max-width: 960px) {
body{
/* something */
background: red;
}
}

And, I made a jQuery function on resize to log the width:


$(window).resize( function() {
console.log( $(window).width() );
console.log( $(document).width() ); /* same result */
/* something for my js navigation */
}

And there a difference with CSS detection and JS result, I have this meta:


<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" name="viewport"/> 

I suppose it's due to the scrollbar (15 px). How can I do this better?


More From » jquery

 Answers
25

You're correct about the scroll bar, it's because the CSS is using the device width, but the JS is using the document width.



What you need to do is measure the viewport width in your JS code instead of using the jQuery width function.



This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/



function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

[#84501] Monday, July 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julian

Total Points: 159
Total Questions: 105
Total Answers: 94

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;