$(window).width() not the same as media query

Mobile Technologies Mobile Computing 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ I am using Twitter Bootstrap on a project. As well as the default bootstrap styles I have also added some of my own //My styles @media (max-width: 767px) { //CSS here } I am also using jQuery to change the order of certain elements on the page when the width of the viewport is less that 767px. $(document).load($(window).bind("resize", checkPosition)); function checkPosition() { if($(window).width() < 767) { $("#body-container .main-content").remove().insertBefore($("#body-container .left-sidebar")); } else { $("#body-container .main-content").remove().insertAfter($("#body-container .left-sidebar")); } } The problem I am having is that the width calculated by $(window).width() and the width calculated by the CSS doesn't seem to be the same. When $(window).width() returns 767 the css calculates it the viewport width as 751 so there seems to be a 16px different. Does anyone know what is causing this and how I could solve the problem? People have suggested that the width of the scrollbar isn't being taken into considering and using $(window).innerWidth() < 751 is the way to go. However ideally I want to find a solution that calculates the width of the scrollbar and that is consistent with my media query (e.g where both conditions are checking against the value 767). Because surely not all browsers will have a scrollbar width of 16px?

Posted on 16 Aug 2022, this text provides information on Mobile Computing related to Mobile Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ If you don't have to support IE9 you can just use window.matchMedia() (MDN documentation). function checkPosition() { if (window.matchMedia('(max-width: 767px)').matches) { //... } else { //... } } window.matchMedia is fully consistent with the CSS media queries and the browser support is quite good: http://caniuse.com/#feat=matchmedia UPDATE: If you have to support more browsers you can use Modernizr's mq method, it supports all browsers that understand media queries in CSS. if (Modernizr.mq('(max-width: 767px)')) { //... } else { //... }

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Mobile Technologies Links