jQuery detect DPI change - javascript

I try now for half a day to detect a DPI change with jQuery.
The scenario is the following:
I have a MacBook Pro (Retina) and a regular screen connected to it. When I move my browser window from the regular one to the MacBooks I want to detect the DPI change.
Obviously events like
$(window).resize(function() {
if (window.devicePixelRatio && window.devicePixelRatio >= 1.3) {
// do retina
} else {
// do standard
}
}
and
$(document).resize(function() {
if (window.devicePixelRatio && window.devicePixelRatio >= 1.3) {
// do retina
} else {
// do standard
}
}
dont work for this, since the resolution just changed physically.
Is there any way to realize this?

I have just tried with my second monitor having a different resolution.
When I move the browser from the first to second screen and back I have to resize the browser so your approach is correct:
var width = screen.width;
var height = screen.height;
$(window).on('resize', function(e) {
if (screen.width !== width || screen.height !== height) {
width = screen.width;
height = screen.height;
console.log('resolution changed!');
}
});
But, if you don't want to adjust the browser height or width this event will be never triggered. In this case another approach can be used as a workaraound:
two functions in order to:
on time basis test the current browser resolution against the old one
stop this timer
use the event
(function ($) {
var width = screen.width;
var height = screen.height;
var idTimer = null;
$.fn.startCheckResolution = function (interval) {
interval = interval || 50;
idTimer = setInterval(function () {
if (screen.width !== width || screen.height !== height) {
width = screen.width;
height = screen.height;
$(this).trigger('resolutionChanged');
}
}.bind(this), interval);
return this;
};
$.fn.stopCheckResolution = function () {
if (idTimer != null) {
clearInterval(idTimer);
idTimer = null;
}
};
}(jQuery));
$(window).startCheckResolution(1000).on('resolutionChanged', function(e) {
console.log('Resolution changed!');
// $(window).stopCheckResolution();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

How about using transition events and a media query
CSS:
body {
transition:font-size 1ms;
font-size:1em;
}
#media only screen and (min-device-pixel-ratio: 2),
only screen and (min-resolution: 192dpi) {
body {
font-size:1.1em
}
}
JS:
$("body").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
$(document).trigger('dpiChange', {pixelRatio: window.devicePixelRatio})
});
$(document).on('dpiChange', function (e, data) {
if (data.pixelRatio >= 1.3) {
// do retina
console.log('retina')
} else {
// do standard
console.log('standard')
}
})
JSBIN:
http://jsbin.com/siramo/1/edit?html,css,js,console
Great Retina Specific Media Query Tutorial:
https://css-tricks.com/snippets/css/retina-display-media-query/

Related

Get the change of dimensions on resize using jQuery

For my web site I am using the following code:
$(window).resize(function (event) {
window.location.reload();
});
Unfortunately when using the site on a mobile device there are minute resize events that occur. I am wanting to put in a tolerance so that these minute changes do not fire this reload.For this I need to know the change in dimensions that occurred in the resize event. I have been looking at the event object however it is huge and ugly.
Thanks in advance :)
You could achieve this by tracking the original window dimensions and then comparing those dimensions with current dimensions (acquired during each resize event) to determine the amount of change.
The following shows how you could trigger a reload if the width changes by a certain total THRESHOLD amount:
var THRESHOLD = 50; // the threshold that must be exceeded to trigger reload
$(window).resize(function(e) {
var width = $(window).width();
// Record the starting window width that the comparison will
// be relative to
if(window.startWidth == undefined) {
window.startWidth = width;
}
// Calculate the total change since first resize event
var widthChange = Math.abs(width - window.startWidth);
// If change exceeds THRESHOLD, trigger reload
if(widthChange > THRESHOLD) {
window.location.reload();
}
})
Building on the helpful comments of JBDouble05 and the helpful answer by Dacre Denny I have made a final solution that fits my needs. Here it is to help others in the future hopefully.
var OGwidth = $(window).width();
var OGheight = $(window).height();
var threshold = 50;
$(window).resize(function (e) {
if (OGwidth < 768) {
var newWidth = $(window).width();
var newHeight = $(window).height();
var widthChange = Math.abs(OGwidth - newWidth);
var heightChange = Math.abs(OGheight - newHeight);
if (widthChange > threshold || widthChange > threshold) {
window.location.reload();
}
} else {
window.location.reload();
}
//reset for next resize
OGwidth = newWidth;
OGheight = newHeight;
})

JavaScript max-width removeAttribute

I have a problem with this code.
This code is checking the resolution of mobile device and open a web page with same resolution. But When I open a page from the mobile device with display width less than 480px and I scroll, the page is not viewed correctly. I want to drop this code for devices with display width less than 480px.
Can you help me?
JavaScript
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 200,
header = document.querySelector("nav");
if (distanceY > shrinkOn) {
header.setAttribute("id","smaller");
} else {
header.removeAttribute("id","smaller");
}
});
}
I dont want: 480px width id smaller to be added.
If I understand you correctly, you want this line of code: header.setAttribute("id","smaller");
to be only executed if the width is greater then 480px. If this is the case, try the following:
var width = document.body.clientWidth;
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 200,
header = document.querySelector("nav");
if (distanceY > shrinkOn) {
if (width > 480) {
header.setAttribute("id","smaller");
}
} else {
header.removeAttribute("id","smaller");
}
});
}

Resize image depending on window height

As per the title, I want to be able to reduce image size when window height becomes smaller.
It's working for reducing part but I want it to get the original height back when window height is greater than specified.
I know this part $('.model').height(); is wrong.
$(window).on('load resize', function() {
var h = $(window).height();
if (h < 850) {
$('.model').height(600);
} else {
$('.model').height();
}
});
You can try to store the height of .model in a variable and restore it like this:
var originalHeight = $('.model').height();
$(window).on('load resize', function() {
var h = $(window).height();
if (h < 850) {
$('.model').height(600);
} else {
$('.model').height(originalHeight);
}
});
try putting height back into (the default) "auto" when you want the original size back?
$(window).on('load resize', function() {
var h = $(window).height();
if (h < 850) {
$('.model').height(600);
} else {
$('.model').css("height","auto");
}
});

JS detect mobile & desktop width & resize AND reload

I have a function that detects the window width and based on that does jquery things that mobile would have and does jquery things for desktop. I have two functions, one that alters content resize and one on reload. What I am trying to do is combine the two into one function. The problem now is anything in the resize function just resizes. Even $("html").width();
Anyone have any ideas or solutions? Thanks.
//ON RESIZE
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(checkTimer, 500);});
function checkTimer() {
var width = $(window).width();
//MOBILE
if (width < 640) {
mobileView();
}
//TABLET
else if (width > 640 && width <966) {
appendFix();
}
//DESKTOP
else if (width >966) {
appendFix();
}
};
//ON RELOAD
var width2 = $(window).width();
//MOBILE
if (width2 < 640) {
mobileView();
};
//TABLET
if (width2 > 640 && width2 <966) {
appendFix();
};
//DESKTOP
if (width2 > 966) {
appendFix();
};
Think I found the solution.
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(mobileSize, 500);});
function mobileSize() {
sizes();
}
$(window).load(function() {
sizes();
});
function sizes() {
var width = $(window).width();
if (width < 640) {
}
else if (width > 640 && width < 966) {
}
else if (width > 966) {
}
}

Detect page zoom change with jQuery in Safari

I have a problem with Safari in a web application that contains a position:fixed element. When the page is zoomed out (smaller 100%) things break and would need to be fixed by calling a function. So I'd like to detect the user's zooming. I found this jQueryPlug-in a while ago:
http://mlntn.com/2008/12/11/javascript-jquery-zoom-event-plugin/
http://mlntn.com/demos/jquery-zoom/
It detects keyboard and mouse events that might lead to a page zoom level change. Fair enough. It works on current FF and IE but not on Safari. Any ideas what could be done to do something simmilar in current WebKit browsers?
It's not a direct duplicate of this question since that deals with Mobile Safari, but the same solution will work.
When you zoom in, window.innerWidth is adjusted, but document.documentElement.clientWidth is not, therefore:
var zoom = document.documentElement.clientWidth / window.innerWidth;
Furthermore, you should be able to use the onresize event handler (or jQuery's .resize()) to check for this:
var zoom = document.documentElement.clientWidth / window.innerWidth;
$(window).resize(function() {
var zoomNew = document.documentElement.clientWidth / window.innerWidth;
if (zoom != zoomNew) {
// zoom has changed
// adjust your fixed element
zoom = zoomNew
}
});
There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:
window.onresize = function onresize() {
var r = DetectZoom.ratios();
zoomLevel.innerHTML =
"Zoom level: " + r.zoom +
(r.zoom !== r.devicePxPerCssPx
? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
: "");
}
Demo
srceen.width is fixed value but where as window.innerWidth value will change as per the zoom effect. please try the below code:
$(window).resize(function() {
if(screen.width == window.innerWidth){
alert("you are on normal page with 100% zoom");
} else if(screen.width > window.innerWidth){
alert("you have zoomed in the page i.e more than 100%");
} else {
alert("you have zoomed out i.e less than 100%");
}
});
Differentiate between window resize, browser zoom change, and system dpi change
;(() => {
const last = {
devicePixelRatio: devicePixelRatio,
innerWidth: innerWidth,
innerHeight: innerHeight,
outerWidth: outerWidth,
outerHeight: outerHeight,
}
const browser = navigator.appVersion.includes('WebKit')
const almostZero = n => n <= 1 && n >= -1
window.addEventListener('resize', () => {
if (last.devicePixelRatio !== devicePixelRatio) {
if (browser ? almostZero(last.innerWidth - innerWidth) && almostZero(last.innerHeight - innerHeight)
:almostZero(last.outerWidth - outerWidth) && almostZero(last.outerHeight - outerHeight)) {
console.log('system wide dpi change')
} else {
console.log('browser level zoom change')
}
} else {
console.log('window resize')
}
last.devicePixelRatio = devicePixelRatio
last.innerWidth = innerWidth
last.innerHeight = innerHeight
last.outerWidth = outerWidth
last.outerHeight = outerHeight
})
})()
Works in Chrome & Firefox on Windows

Categories

Resources