$(window).resize(); not working as expected [duplicate] - javascript

This question already has answers here:
$(window).resize(); doesn't work
(5 answers)
Closed 7 years ago.
I want on set of functionality to be used on screen sizes larger than 768px and another set to be used on everything smaller than that. I need the .resize() so I can know when a user is turning their tablet or phone between landscape and portrait views.
The code on the inside of the .resize() event works fine if i refresh the page but it's as if the event isn't being triggered. Any thoughts?
<script>
jQuery(document).ready(function($){
function mobileFilterMenu(){
var screenTest = $(window).width();
if (screenTest >= 769){
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop(),
elementOffset = $('.inventory-search > .col-md-9').offset().top,
distance = (elementOffset - scrollTop);
if(distance <= 0){
$('.filter-form').css('top', Math.abs(distance));
}else{
$('.filter-form').css('top', 0);
}
});
}else{
var vHeight = $(window).height() - $('#switch').height() - $('#primary-menu-toggle').height();
$('.filter-form').css('height', vHeight + 'px');
vTextHeight = vHeight - 20;
$('.wpv-filter-form').css('height', vTextHeight + 'px');
objNegHeight = (vHeight * -1) + 50;
$('.filter-form').css('top', objNegHeight + 'px');
var i;
$('#switch').click(function(){
if (i === 0){
$('.filter-form').css('top', objNegHeight + 'px');
i++;
}else{
$('.filter-form').css('top', '50px');
i = 0;
}
});
}
}
mobileFilterMenu();
$(window).resize(mobileFilterMenu());
});
</script>

Just change this part of your code. This should fix your problem.
$(window).resize(mobileFilterMenu);
Instead of passing mobileFilterMenu(), pass this mobileFilterMenu
The parameter inside the $window.resize should have a function not a function call.
Hope this solves your issue.

You should use media queries to apply CSS based on viewport dimensions not code!
Media queries enable us to create a responsive experience, where
specific styles are applied to small screens, large screens and
anywhere in between. The media query syntax allows for the creation of
rules that can be applied depending on device characteristics.
#media (query) {
/* CSS Rules used when query matches */
}
While there are several different items we can query on, the ones used
most often for responsive web design are min-width, max-width,
min-height and max-height.
<link rel="stylesheet" media="(max-width: 640px)" href="max-640px.css">
<link rel="stylesheet" media="(min-width: 640px)" href="min-640px.css">
<link rel="stylesheet" media="(orientation: portrait)" href="portrait.css">
<link rel="stylesheet" media="(orientation: landscape)" href="landscape.css">
<style>
#media (min-width: 500px) and (max-width: 600px) {
h1 {
color: fuchsia;
}
.desc:after {
content:" In fact, it's between 500px and 600px wide.";
}
}
</style>
https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/use-media-queries?hl=en#apply-media-queries-based-on-viewport-size

Related

Different measurement between #media querys and jquery

I notticed when resizing the window, that the effects applied from the responsive #media querys and the effects applied from the jQuery are not at the same point of width.
Is is dued to the browser? Is there a solution for that, or a way to calculate the difference between CSS and JS?
My CSS:
#media only screen
and (min-width : 768px)
and (max-width : 1024px) { }
My jQuery:
$(document).ready(function(){
if($(this).width() < 1024 && $(this).width() > 768) {
} else {
}
$(window).on('resize', function(){
if($(this).width() < 1024 && $(this).width() > 768) {
} else {
}
});
});
To avoid this difference at the moment, my solution is something like that: I have a #selector declared with the display:none when it's between 768px and 1024px. Then, in the jQuery code, instead of using the size < 1024 and > 768 I'm using this:
if($("#selector").is(":hidden")) { }
But, is there a better way to combine width from the #media querys and the jQuery without differences? Thanks.
UPDATE: I already found a solution explained here: https://stackoverflow.com/a/11310353/3018860. That occurs because «the CSS is using the device width, but the JS is using the document width».

detect browser size and apply css for every resolution

I have this function that I use to apply some css to a menu when browser is resized or when the menu is rendering on different resolutions.
My problem is this, why the browser is not interpreting correctly my function? because when I resize my browser in full mode from half mode the browser interprets only '800-1024' resolution but if I do ctrl+f5 in browser (clear all) interprets correctly my resolution so what is wrong in my function?
function renderMenuCorection(){
if ($('#containerHeader').exists()) {
var resizeObject = {
'0-640': '9px,2px,-3px,12px',
'640-800': '10px,2px,-5px,12px',
'800-1024': '10px,8px,-8px,15px',
'1024-1300': '12px,12px,-13px,11px',
'1300-2000': ',20px,-21px'
}
var win = $(window);
var win_width = win.width();
if (win_width > 0 && win_width <= 640) {
var value = getValueByKey(resizeObject, '0-640');
modifayMenu(value);
}
else
if (win_width > 640 && win_width <= 800) {
var value = getValueByKey(resizeObject, '640-800');
modifayMenu(value);
}
else
if (win_width > 800 && win_width <= 1024) {
var value = getValueByKey(resizeObject, '800-1024');
modifayMenu(value);
alert("I'm on: 800-1024 ," + win_width);
}
else
if (win_width > 1024 && win_width <= 1300) {
var value = getValueByKey(resizeObject, '1024-1300');
modifayMenu(value);
alert("I'm on: 1024-1300 ," + win_width);
}
else
if (win_width > 1300 ) {
var value = getValueByKey(resizeObject, '1300-2000');
modifayMenu(value);
}
}
}
function modifayMenu(value){
var vals = value.split(',')
$('#containerHeader').find('.roundMenuLi').each(function(index, item){
$(item).find('a').css('font-size', vals[0]);
$(item).css('padding-right', vals[1]);
$(item).css('padding-left', vals[1]);
$(item).find('#secondUl').css('margin-left', vals[2]);
$(item).css('padding-bottom', vals[3]);
});
}
function getValueByKey(obj, myKey){
$.each(obj, function(key, value){
if (key == myKey) {
returnValue = value;
}
});
return returnValue;
}
Thank you !
Use CSS3 and its media queries. Example:
#media (max-width: 500px) {
/* some CSS for small resolution */
}
#media (min-width: 1000px) {
/* some CSS for large resolution */
}
you main you want to create a responsive design this link can help you.
building responsive design you must consider
Flexible Grid
Flexible Images
Media Quires
/* below code play important part of your responsive design without that you cannot achieve what you want */
<meta name="viewport" content="width=device-width" /> /* put this before the end tag of head */
#media (max-width: 320px) {
}
#media (min-width: 720px) {
}
It's hard to tell from your code, but most likely you are only calling the function once on pageload. In order to make this do what you want, you will have to attach an event listener and call the code each time the window is resized.
As commented above, consider researching Responsive Web Design to utilize native browser functionality so you don't have to roll your own script to do this. A good place to start is an A List Apart article under the same name.
Media-queries are the best solution as Pavel remarks, besides they're much faster than all the access to the DOM you're making using your code.
The compatibility problem with IE8 can be solved using a JavaScript pluging called Respond.js. Haven't tried it but it seems a good solution to your problem.

apply classname (css) based on screen resolution

I have a problem when I am working on resolution base application.
If I have 1024 by 768 resolution my application should be 100% (table Layout). If I have above 1024 by 768 resolution the application should be in center align (table width is 80%).
function MOSTRA() {
var SCR = screen.availWidth;
var BRW = window.outerWidth;
if (BRW < SCR) {
document.getElementById('sample').className = 'maintable';
} else {
document.getElementById('sample').className = 'maintable1';
}
}
window.onresize = MOSTRA;
window.onload = MOSTRA;
I have used the above code but this is not working.
Hi all i have checked with putting alert in required place. Now i know where the problem is occurring in window.outerWidth it seems because when i alert in that area i am getting undefined in IE. It seems Ie is not supporting outerwidth. I have taken the above code from the below link.
http://jsfiddle.net/Guffa/q56WM/
Please helpe me.
This is a urgent issue
Thanks in advance
Use CSS3 Media Queries:
#media screen and (min-width: 1024px) and (min-width: 768px)
{
/* Center table! */
}
Also possible:
<link rel="stylesheet" media="screen and (min-width: 1024px) and (min-width: 768px)" href="example.css" />
JS variant (because OP didn't want CSS 3):
if (window.screen.width >= 1024 && window.screen.width >= 768) {
document.head.innerHTML += '<link rel="stylesheet" href="centerTable.css" type="text/css" />'
}
Pragmatically include style-sheets based on display width, media type: http://www.w3.org/TR/css3-mediaqueries/

CSS media queries and jQuery window .width() do not match

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?
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' ] };
}
I found following code on http://www.w3schools.com/js/js_window.asp:
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Practically its working the same way as the answer in #Michael Bird's answer, but it's more easy to read.
Edit: I was looking for a method to give exactly the same width as it is used for css media queries. But the suggested one does not work perfect on Safari with scrollbars, sorry. I ended up using modernizr.js in one central function and in the rest of the code I just check if display type is mobile, tablet or desktop. As I am not interested in the width, this works fine for me:
getDisplayType = function () {
if (Modernizr.mq('(min-width: 768px)')){
return 'desktop';
}
else if (Modernizr.mq('(min-width: 480px)')){
return 'tablet'
}
return 'mobile';
};
window.innerWidth is what you need.
if (window.innerWidth < 768) works for 768 break point in CSS
Workaround that always works and is synced with CSS media queries.
Add a div to body
<body>
...
<div class='check-media'></div>
...
</body>
Add style and change them by entering into specific media query
.check-media{
display:none;
width:0;
}
#media screen and (max-width: 768px) {
.check-media{
width:768px;
}
...
}
Then in JS check style that you are changing by entering into media query
if($('.check-media').width() == 768){
console.log('You are in (max-width: 768px)');
}else{
console.log('You are out of (max-width: 768px)');
}
So generally you can check any style that is being changed by entering into specific media query.
My experience was that the media query width tracks document.body.clientWidth. Because of a vertical scroll bar coming and going, checking document, window, or viewport().width could cause my Javascript to run late--after the media query rule change, depending on the height of the window.
Checking document.body.clientWidth allowed my script code to execute consistently at the same time the media query rule took effect.
#media (min-width:873px) {
//some rules
}
...
if ( document.body.clientWidth >= 873) {
// some code
}
The Andy Langton code put me onto this--thanks!
Hi i use this little trick to get JS and CSS work together easily on responsive pages :
Test the visibility of an element displayed or not on CSS #media size condition.
Using bootstrap CSS i test visibility of a hidden-xs class element
var msg = "a message for U";
/* At window load check initial size */
if ( $('#test-xsmall').is(':hidden') ) {
/* This is a CSS Xsmall situation ! */
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
/* > 768px according to CSS */
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
/* And again when window resize */
$(window).on('resize', function() {
if ($('#test-xsmall').is(':hidden')) {
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
});
#media (min-width: 768px) {
.hidden-xs {
display: block !important;
}
}
#media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
.redthing-on-xsmall {
/* need a scrollbar to show window width diff between JS and css */
min-height: 1500px;
}
.redthing {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- the CSS managed Element that is tested by JS -->
<!-- class hidden-xs hides on xsmall screens (bootstrap) -->
<span id="test-xsmall" class="hidden-xs">THIS ELEMENT IS MANAGED BY CSS HIDDEN on #media lower than 767px</span>
<!-- the responsive element managed by Jquery -->
<div class="redthing-on-xsmall">THIS ELEMENT IS MANAGED BY JQUERY RED on #media max width 767px </div>
Css media query is equal to window.innerWidth. Css Media Queries calculate the scrollbar as well.
The simple and reliable way of doing this is to use Media Queries.
To demonstrate, I want to check if the screen width is greater than or equal to 992px (Bootstrap's large device):
function isLargeDevice() {
if (window.matchMedia("(min-width: 992px)").matches) {
return true;
}
return false;
}
If you are using Modernizer then it's a bit easier, here I want to check if the screen is smaller than Bootstrap's large screen (992px)
function isSmallerThanLargeScreen() {
if (Modernizr.mq('(max-width: 991px)')) {
return true;
}
return false;
}

jQuery Dynamic Background-Postion for iPhone

Forgive me, I am a total n00b with javascript! I have a complicated request that I've been trying to put together for hours I think I have the pieces, but I have a poor understanding of javascript and jQuery syntax, can someone help me put this together?
First, this code should detect via UserAgent string if the device is an iPhone (Note: I'm not sure if this works for all mobile devices... any suggestions for better conditional statements that will catch ALL iPads, iPhones, etc. - anything that uses viewport rather than scrollbars)
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
{
// do stuff
}
else
{
// do nothing
}
}
</script>
Next piece of the puzzle is detecting the height of the viewport. It's important that this script be conditional and apply only to devices that utilize viewport and NOT scrollbars, otherwise I screw the site up for non-mobile users. I only need to alter background-position on the y axis, trying to prevent the background image from disappearing when mobile users slide the viewport.
var viewportHeight = $(window).height();
I found this snippet of code that utilizes the "parralax" effect - where scrolling your position affects the background-position.
$(function(){
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
xAdd = 0;
}
$('#body').css('background-position',xAdd + 'px 100%');
},10);
}); }
Can someone help me stitch all of this together... PLEASE?!
I'm thinking it should look something like this:
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
$(function(){
var viewportHeight = $(window).height();
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
yAdd = 0;
}
$('#body').css('background-position',yAdd + 'px 100%');
},10);
}); }
}
else
{
''
}
}
</script>
This might not be exactly what your looking for but you can detect iphone and ipad and ipod devices through CSS like this
<link rel="stylesheet" type="text/css" href="css/iphone.css" media="only screen and (max-device-width: 480px)" />
<link rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px)" href="css/ipad.css" type="text/css" />
But I kno you need it through jQuery here is what you might do instead
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// do something
} else {
//do this
}
});
the only problem is this code is not specific to iPhone, iPad, iPod and so on
as far as the background-image Fixed doesn't work I know you know that makes sense why it doesn't but it sucks and I have not explored a solution for this
I don't have an official answer for this yet, but I'm CLOSE... Read Over here
https://stackoverflow.com/questions/4719469/patching-this-code-to-apply-dynamic-iphone-background-position
I've found a way to dynamically set the "top: x" property based on scroll position (at least it works on my iPhone)... but I still need help putting it all together!

Categories

Resources