CSS Media Query and Javascript/jQuery don't match up - javascript

In my CSS I have a media query like so:
#media (min-width: 800px) { /* styles */ }
And then in my jQuery, I'm targeting the window width and performing some actions.
Edit: as per the answers below, I have changed this function but my JS and CSS still didn't align. The problem was fixed by using the Modernizr function as specified in the accepted answer.
$(window).resize(function() {
var viewportWidth = $(window).width();
if (viewportWidth >= 800) {
// do something
}
});
The problem is that while the jQuery is executing bang on 800px or more, the CSS is kicking in at 740px.
Is there a known problem with these not aligning? Or could there be something on my page affecting the CSS and why it's 740px not 800px? Maybe there's something else I should be using instead of $(window)?
Edit: I've tested in Safari and it works perfectly. In Chrome and Firefox, the jQuery functions run spot on to 800px and so does the CSS. But in Chrome, the CSS actually runs after 740px, even though the media query is 800px - how can I get these to align perfectly?

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
}
});

Move your width check, or else the viewportWidth variable will always be the same thing:
$(window).resize(function() {
var viewportWidth = $(this).width();
if (viewportWidth >= 800) {
// do something
}
});

Valid code would be:
$(window).resize(function() {
var viewportWidth = $(window).width();
if (viewportWidth >= 800) {
// do something
}
});
Everytime window resizes the new value will be stored in viewportWidth variable. In your code viewportWidth gets the only value of the $(window).width() when the page was loaded.

What I just tried, and it seems to work, is to use the CSS media query to style an object, and then use javascript to test if the object has that style. Javascript is asking CSS what the answer is, rather than having two parts of the page determine it separately:
CSS:
#media (min-width: 800px) {
#viewType {width:3px;}
}
HTML :
<div id="viewType" style="display:none"></div>
JavaScript:
var answer = ($("#viewType").width()==3)

I agree with Steve answer. the jquery(window).width(); is does not match with the media queries and even doesn't provide accurate window width size. here is my answer taken from Steve and modified.
CSS :
#media (max-width: 767px) {
//define your class value, anything make sure it won't affect your layout styling
.open {
min-width: 1px !important;
}
}
.open {
min-width: 2px;
}
Js :
// when re-sizing the browser it will keep looking for the min-width size, if the media query is invoked the min-width size will be change.
$(window).on('resize orientation', function() {
var media = $('.open').css('min-width');
if( media == '1px') // means < 767px
{
// do your stuff
}
});
That's it~ hope it help.

Related

How to run a jQuery Function in smaller width?

I want to do a something in a smaller width of screen But I have a problem. I'm creating a Responsive Navbar, So I want to show a Button when It is in small width & toggling the Menu. But when I hide the Menu in smaller width, It doesn't show the Menu in wider width Because of Hiding in jQuery ...
So I wanted to make jQuery Codes run JUST in smaller width, I wrote this But It doesn't work :
$(window).resize(function() {
if($(window).width() < '48em') {
$('.ji-toggle-btn').click(function() {
$(this).parent().find('ul').toggle();
});
}
});
The proper way to show/hide a button is with a media query in CSS:
.css example:
.ji-toggle-btn {
display: none;
}
#media (min-width: 48em) {
.ji-toggle-btn {
display: block;
}
}
.scss example:
.ji-toggle-btn {
display: none;
#media (min-width: 48em) {
display: block;
}
}
I mocked up a sample of how to do a responsive sidebar:
http://codepen.io/staypuftman/pen/dGOMYO
What you'll notice in this example is how little JS is used. Targeting a .toggle class and using css transitions will get you where you want to go. You're overthinking this approach with the JS.
Your problem is that you're assigning a behavior on smaller resolution. You practically want to assign a click event only when the window size is smaller than 48 em.
With simple words - just remove the click event:
$(window).resize(function() {
if($(window).width() < '48em') {
$('.ji-toggle-btn').parent().find('ul').toggle();
}
});
EDIT I agree with the guy above about the CSS. Those things basically should be done with media queries.
$(window).width() returns an int (screen width in pixels). In order to get that value in ems you need to divide that buy the body's font-size, then compare that with just '48' not '48em'. For example:
$(window).resize(function() {
if(($(window).width() / parseFloat($("body").css("font-size"))) < 48) {
// Do stuff here...
}
});

Button fixed to page when scrolling in mobile view with Javascript

hoping to get some JS/CSS help here. I need to have the checkout button on a page of mine go to the top of the page and become fixed if the user can no longer see it scrolling down the page in mobile view. I'm hoping someone can help! The one thing messing me up is that I can't use jQuery
![function checkoutScroll() {
var button = document.querySelector('.cartSidebar__checkoutButton');
window.addEventListener('scroll', function () {
var distanceFromTop = document.body.scrollTop;
if (distanceFromTop === 0) {
button.style.position = 'static';
button.style.top = 'auto';
}
if (distanceFromTop > 0) {
button.style.position = 'fixed';
button.style.top = '0px';
}
});
}
What you are trying to achieve can be done through CSS which would make more sense as it's a visual / UI task. I would add top margin equivalent to the css height of your button and leave it as fixed top. As a benefit, you would be able to take advantage of the media queries to limit the CSS rules to the mobile view.
#media screen and (max-width: 960px) {
.container{
margin: 3em;
}
.checkout_button{
display:block;
position:fixed;
top:0;
left:0;
width:100%;
}
}
something very simple like https://jsfiddle.net/f19Lus43/
If you want to stay in javascript for some obscure reasons ( I can't say compatibility because of document.querySelector is working only on evolved browser ) it's up to you but having an example of your code would help us respond :)
So I take it you want the function to only run on smaller screens/browser viewports? Is that what you mean by "mobile view"? I've been using this for a while. Not sure if its better than Glen's solution but it's worked for me without fault. First we define our functions:
function updateViewportDimensions() {
var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
return { width:x,height:y };
}
// setting the viewport width
var viewport = updateViewportDimensions();
function detectMob() {
viewport = updateViewportDimensions();
if (viewport.width <= 768) {
return true;
} else {
return false;
}
}
Then every time you need to check if the size of the viewport is less than 768 pixels wide you do:
if (detectMob){
//your code here
}

scaling divs and images css/javascript depending on the screen

I have div which has inside few divs, few images and two selects. I want to make my main division and all of its content to automatically resize depending on the screen. How can I do it?
Thank you :)
You use media queries for this. It is called responsive design
#media screen and (max-width: 699px) {
div {
width: 40px;
}
}
This will essentially change the width of div to 40px only if the screen width is less than 699px
Further reference:
CSS-Tricks
Here is a tried-and-tested script which even accomodates prehistoric browsers such as IE4. It takes the viewport approach, which means divisions can be updated when a user resizes their browser window.
<script>
window.onResize = function() {
if (window.innerWidth) { // All browsers but IE
myViewportWidth = window.innerWidth;
myViewportHeight = window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
// These functions are for IE6 when there is a DOCTYPE
myViewportWidth = document.documentElement.clientWidth;
myViewportHeight = document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
// These are for IE4, IE5, and IE6 without a DOCTYPE
myViewportWidth = document.body.clientWidth;
myViewportHeight = document.body.clientHeight;
}
// now call customResize with your chosen new dimensions
// you'll probably need to insert a bit of arithmetic here:
// *calculate new values here*
customResize( MY_NEW_X_VALUE, MY_NEW_Y_VALUE );
}// function
</script>
Once you have the viewport dimensions you can resize your main division according to the specific dimensions of the viewport.
I generally use one main division for the content placed inside the 'body' element for convenience. Then modify the following script according to the dimensions you need.
<script>
function customResize(newWidth, newHeight){
var X = newWidth;
var Y = newHeight;
var e = document.getElementById('mainDiv').style.width = 'X';
var f = document.getElementById('mainDiv').style.height = 'Y';
</script>
Take care to test the code with different browsers however - sometimes odd versions of browsers can return unusual values.

Detect if webapp is in landscape orientation and add padding-top

What I want the script:
-detect if site is in standalone app
-detect if site is in landscape
-add padding-top to header
if (window.navigator.standalone == true && window.innerWidth > window.innerHeight){
$('header').css('padding-top','20px');
}
Use media queries for device-conditional layout:
#media screen and (orientation:landscape) {
header {
padding-top:20px;
}
}
If the standalone property is really important, detect it in Javascript and add a class to the body:
if (window.navigator.standalone == true)
$('body').addClass('standalone');
Then use it in your CSS to apply extra requirements:
.standalone header {
padding-top:20px; /* only applied if standalone */
}
You can of course combine the media query with this.
I figured it out
if (window.navigator.standalone){
$(window).resize( function(){
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$('header').css('padding-top','20px');
}
else{
$('header').css('padding-top','0px');
}
});
}

Detecting a screen's width with Javascript

if(screen.availWidth > 850){
//Do this
} else {
//Do this
}
This is what I have right now. My issue right now is if someone was to zoom in to the page, I want the width to change as it will affect how the page is displayed.
Shouldn't you be more worried about someone resizing their browser window? Not everyone keeps their browsers maximized.
To do this:
if( (window.innerWidth || document.documentElement.clientWidth) > 850) {
// do something
}
else {
// do other thing
}
I'm fairly sure this takes the zoom into account, but I've never tested that.
Bind an event handler to the window.onresize event:
window.onresize = function(event) {
if (screen.availWidth > 850) { ... }
};
If you use jQuery:
$(window).resize(function(){
if ($(window).width() > 850) { ... }
});
Besides, if you want to create a responsive design, consider using CSS media queries. This automatically adapts the page if the user zooms or resizes the browser window and also works if the user has JavaScript deactivated.
/* CSS */
#media (min-width: 850px) {
/* style */
}

Categories