CSS media queries and jQuery window .width() do not match
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' ] };
}
$(window).width() not the same as media query
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 {
//...
}
Window width inconsistent between jQuery and CSS media query
You need to check the width
of viewport
like,
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' ] };
}
Viewport Source
Or you can use innerWidth() like,
if($(window).innerWidth() <= 751) {
$("body").css('background','red !important'); // background red
} else {
$("body").removeAttr('style'); // remove style attribute
}
You can use matchmedia if you are not care about IE
for egs,
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}
For all browsers you can try
if (Modernizr.mq('(max-width: 767px)')) {
//...
} else {
//...
}
See modernizr mq
CSS Media Query and Javascript/jQuery don't match up
You can use Modernizr to execute the media query in JS (the mq()
method will return a boolean):
$(window).resize(function() {
if (Modernizr.mq('(min-width: 800px)')) {
// do something
}
});
jQuery window width not equal to CSS's window width
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
- Add a hidden element to your page,
- Use media queries to alter the
max-width
property of that element, - Read back the
max-width
property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
@media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
jQuery and CSS media query dont match
Apply display: none
to your footer by default. Then, wrap the code that checks the scroll position in an if
statement that checks the window's width.
jQuery(window).scroll(function() { if (jQuery(window).width() <= 780) { if (jQuery(this).scrollTop() > 100) { jQuery('#footer').fadeIn(); } else { jQuery('#footer').fadeOut(); } }});
body { background: #eee; height: 300vh;}
#footer { display: none; background: #dfd;}
@media only screen and (max-width: 780px) { #footer { position: fixed; right: 0; bottom: 0; left: 0; padding: 1rem; z-index: 10; }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer id="footer">This is my footer.</footer>
Error when using media queries with jQuery
The window.matchMedia()
method:
runs the specified CSS media query and compares it to the current window state once. To use window.matchMedia() in a responsive manner, to make your code react to a CSS media query whenever the window state changes, you can use its methods/event handlers.
More here www.w3schools.com/win_matchmedia.
To add event listeners for the state change do this:
// media query handler function
function myCSS_handler(x)
{
if (x.matches)
{
// the screen width is less or equal to 767px
$(".services").css("display", "block");
$(".personal-detail").css("display", "none");
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
$(".personal-detail").css({ "opacity": "0.5", "color": "black" });
}
else
{
// the screen width is greater than 767px
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
$(".personal-detail").css({ "opacity": "0.5", "color": "black" });
$(".services").css({ "opacity": "1", "color": "#fff" });
}
}
// on DOM ready
$(document).ready(function()
{
$(".billing-information").hide();
$(".services-information").css("display", "none");
$("#next").click(function()
{
var x = window.matchMedia("(min-width: 767px)")
myCSS_handler(x) // Call listener function on button press
x.addListener(myCSS_handler) // Attach listener function on state changes
});
});
Or you can use the window resize function
like this without the media queries
(i added some example functions so the code is more readable):
// function to handle CSS on screen width change
function dynamic_CSS()
{
// get window width
var width = $( window ).width();
// alert("window width is " + width);
// if width is less or equal to 767px call function widthFrom_0_to_767()
if(width <= 767) widthFrom_0_to_767();
else if(width > 767 && width <= 990) widthFrom_767_to_990();
else if(width > 990 && width <= 1300) widthFrom_990_to_1300();
else if(width > 1300 && width <= 1600) widthFrom_1300_to_1600();
else widthFrom_above_1600();
}
// example function for screen width up to 767px
function widthFrom_0_to_767()
{
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
// ...
}
// on DOM ready
$(document).ready(function()
{
$(".billing-information").hide();
$(".services-information").css("display", "none");
// calls it upon click
$("#next").click(function()
{
dynamic_CSS();
});
// on window resize
$(window).resize(function()
{
// also calls it upon window resize
dynamic_CSS();
});
});
Related Topics
Disable Hover Effects on Mobile Browsers
What Are Alternatives to Extjs
Create a File Using JavaScript in Chrome on Client Side
How to Persist a Es6 Map in Localstorage (Or Elsewhere)
Jquery Function Not Binding to Newly Added Dom Elements
Password-Check Directive in Angularjs
How to Use Redis Publish/Subscribe with Nodejs to Notify Clients When Data Values Change
D3 Appending Text to a Svg Rectangle
Get Path Params in React-Router V4
JavaScript Getelementbyid Based on a Partial String
How to Get Index in Handlebars Each Helper
Sort an Array with Arrays in It by String
Get All User Defined Window Properties
Detect When a Window Is Resized Using JavaScript
How to Access Object Property with Invalid Characters