jQuery widthRatio returning NaN on IE8 - javascript

I have fullscreen site. When I click to my page, image resize fullscreen directly. It's working on IE 9-10, Chrome, Firefox. But don't working on IE8.
My JS code:
$(window).resize(function () {
$("#backgrounds img").each(function (k, v) {
$backgroundImg = $(this);
windowWidth = window.innerWidth
windowHeight = window.innerHeight
imageWidth = 1366
imageHeight = 900
widthRatio = windowWidth / imageWidth;
heightRatio = windowHeight / imageHeight;
console.log('width: ' + widthRatio)
console.log('height: ' + heightRatio)
if (widthRatio > heightRatio) {
$backgroundImg.width(windowWidth);
$backgroundImg.height(imageHeight * widthRatio);
} else {
$backgroundImg.height(windowHeight);
$backgroundImg.width(imageWidth * heightRatio);
}
$backgroundImg.css({ marginLeft: -$backgroundImg.width() / 2 });
$backgroundImg.css({ left: "50%" });
});
});
When I check e.g. console on Chrome, get this data:
width: 1.3711566617862372
height: 0.7488888888888889
But when I check this function on IE8, get this:
height: NaN
width: NaN
Searched on StackoverFlow but don't find solution. How can I fix it? Thank you.

The innerWidth is NOT supported by IE8 ,
Use this for all support ,
var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

Yes, it's innerWidth support problem and solved by this link:
https://stackoverflow.com/a/18136089/1485921
So, added this function on my js file:
(function (window, html, body) {
if (!window.innerWidth) Object.defineProperty(window, 'innerWidth', {
get: function () { return html.clientWidth }
});
if (!window.innerHeight) Object.defineProperty(window, 'innerHeight', {
get: function () { return html.clientHeight }
});
}(this, document.documentElement, document.body));
Thank you!

Related

jQuery detect DPI change

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/

convert jquery code to javascript

I have a jquery script that i want to convert in javascript.
Jquery:
<script type="text/javascript">
$(document).ready( function() {
addCssTransform();
$( window ).resize(function() {
addCssTransform();
});
function addCssTransform() {
var docWid = $(document).width();
var w = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
var actualWidth = w - (w - docWid);
var zoom = actualWidth / 1280;
var zoomRatio = zoom *100;
console.log(zoomRatio);
if(actualWidth > 1280) {
$('html').css( 'font-size', + zoomRatio+ '%' ); /* IE 9 */
}
}
});
</script>
I have tried and here is the output. But it is not working and giving error in console.
javascript:
<script type="text/javascript">
addCssTransform();
window.addEventListener('resize', function(event){
addCssTransform();
});
function addCssTransform() {
var docWid = document.body.clientWidth;
var w = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
var actualWidth = w - (w - docWid);
var zoom = actualWidth / 1280;
var zoomRatio = zoom *100;
console.log(zoomRatio);
if(actualWidth > 1280) {
document.getElementsByTagName("html").style.fontSize = zoomRatio + '%';
//$('html').css( 'font-size', + zoomRatio+ '%' ); /* IE 9 */
}
};
</script>
It seems there is an error in line:
document.getElementsByTagName("html").style.fontSize = zoomRatio + '%';
getElementsByTagName returns an array-like NodeList object, not an element. You can't set style on it. You have to loop over it and set the style on each member (which will be elements) of it in turn.
<script type="text/javascript">
// Add 'DOMContentLoaded' event
document.addEventListener('DOMContentLoaded', function () {
addCssTransform();
// NOTE: Just reference the function. Don't create new one unless needed
window.addEventListener('resize', addCssTransform, false);
function addCssTransform() {
var docWid = document.body.clientWidth;
var w = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
var actualWidth = w - (w - docWid);
var zoom = actualWidth / 1280;
var zoomRatio = zoom *100;
console.log(zoomRatio);
if(actualWidth > 1280) {
// If you are adding styles to 'html' element, use available 'document.documentElement' property
document.documentElement.style.fontSize = zoomRatio + '%';
//$('html').css( 'font-size', + zoomRatio+ '%' ); /* IE 9 */
}
}
}, false);
</script>
Add DOMContentLoaded event and place your JavaScript inside it.
Reference the function.
You can write the below code
window.addEventListener('resize', function (event) {
addCssTransform();
}, false);
as
window.addEventListener('resize', addCssTransform, false);
Use document.documentElement to access 'html' element
You are calling the addCSSTransform function before it is defined. Move the call to after the function declaration, i.e:
window.addEventListener('resize', function(event){
addCssTransform();
});
function addCssTransform() {
var docWid = document.body.clientWidth;
var w = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
var actualWidth = w - (w - docWid);
var zoom = actualWidth / 1280;
var zoomRatio = zoom *100;
console.log(zoomRatio);
if(actualWidth > 1280) {
document.getElementsByTagName("html").style.fontSize = zoomRatio + '%';
//$('html').css( 'font-size', + zoomRatio+ '%' ); /* IE 9 */
}
};
addCssTransform();
as suggested by Vigneswaran, you may wish to bind the call to a DOMContentLoaded event (equivalent to $(document).ready) as follows:
document.addEventListener('DOMContentLoaded', addCssTransform);
The suggestions above regarding nodeLists returned from getElementsByTagName are also correct (the clue's in the name - getElementsByTagName). There will (or should!) only ever be one html element, so you can safely replace document.getElementsByTagName("html").style with document.getElementsByTagName("html")[0].style
getElementsByTagName returns an nodeList over which you would need to loop.
An alternative would be to use querySelector which returns a single element instead:
document.querySelector('html');

Iframe height definition in IE 7

I have a problem with resizing iframe content in IE7.
I have an external iframe
<IFRAME id=fl_game src="my_iframe_page" frameBorder=0 allowTransparency scrolling=no></IFRAME>
with width=100%, height=93%
and add my page into it. Here is a page body
<div id="container">
<div id="game-box">
<div id="flashcontent">
</div>
</div>
</div>
<script type="text/javascript">
swfobject.embedSWF("<%=application.getContextPath()%>/flash/<%= request.getParameter(PARAM_GAME) %>/game.swf", "flashcontent", gameWidth, gameHeight, "10.1", "/flash/expressInstall.swf", flashvars, params);
</script>
On my page I add resize events.
if (window.addEventListener) {
window.addEventListener("load", resizeGame, false);
window.addEventListener("resize", resizeGame, false);
} else if (window.attachEvent) {
window.attachEvent("onload", resizeGame);
window.attachEvent("onresize", resizeGame);
} else {
window.onload = function() {resizeGame();};
window.onresize = function() {resizeGame();}
}
Here is my resizeGame function
function resizeGame(isIEResize) {
var flash = document.getElementById('flashcontent');
var screen = screenSize();
var width = screen.width;
var height = screen.height;
var left = 0;
var top = 0;
if (height * 1.5 > width) {
height = width / 1.5
} else {
width = height * 1.5;
}
flash.width = width;
flash.height = height;
document.getElementById('flashcontent').style.width = width + 'px';
document.getElementById('flashcontent').style.height = height + 'px';
document.getElementById('flashcontent').style.top = '50%';
document.getElementById('flashcontent').style.left = '50%';
if (width < screen.width) {
left = (screen.width - width) / 2 + left;
}
if (height < screen.height) {
top = (screen.height - height) / 2;
}
document.getElementById('game-box').style.top = top + 'px';
document.getElementById('game-box').style.left = left + 'px';
}
function screenSize() {
var w, h;
w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
return {width:w, height:h};
}
And here is a question:
In IE7 function screenSize() gives me wrong height on load. Under other browsers and IE>7 function screenSize() gives me correct height. That's why I can't resize my content properly.
And when I explicitly resize a window, function screenSize() starts to give correct height.
Here some screens before explicit resizing and after it.
screenSize() gives strange height ONLY in IE7.
I am ready to add any extra information to find a reason of this situation.
I hope someone can help me to find out how to define iframe height in IE7. Any help will be useful.

"Zooming" elements on a page while keeping the centre of enlargement in the centre of the window

I'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.
On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)
I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..
Any ideas?
Well, here's my take.
Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.
This works as expected with no side effects.
Here's a working demo you can test:
http://jsfiddle.net/YFPRB/1/
(You need to click on the pane with the baboon first.)
HTML
<body>
<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />
</body>
CSS
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}​
jQuery
EDIT: Thanks to #stagas for the reminder to clean up redundancies.
var $img = $('img'); // Cache the image. Better for performance.
$img.draggable();
$img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
.css({top: ($('body').height() / 2) - ($img.height() / 2)})
$(document).keydown(function(event) {
if (event.keyCode == 38) {
var adjustment = 1.25;
} else if (event.keyCode == 40) {
var adjustment = 0.8;
} else {
return;
}
var offset = $img.offset();
var width = $img.width();
var height = $img.height();
var newWidth = width * adjustment;
var newHeight = height * adjustment;
var diffWidth = newWidth - width;
var diffHeight = newHeight - height;
var hcenter = $('body').width() / 2;
var vcenter = $('body').height() / 2;
var leftPercent = (hcenter - offset.left) / width;
var topPercent = (vcenter - offset.top) / height;
$img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});
$img.width(newWidth).height(newHeight);
});​
This is what I came up, it works as you say except the image will always go to the center after zooming in or out:
$('document').ready(function() {
zoomimg=$('#zoomimg'); // we store this in a variable since we don't need to traverse the DOM every time -- this is faster
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
zoomimg.css({'position': 'absolute', 'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)}).draggable();
$(document).keydown(function(event) {
event = event || window.event;
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
if (event.keyCode == 38) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*1.2).height(height*1.2);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else if (event.keyCode == 40) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*0.8).height(height*0.8);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else {
return
}
});
});
You should put an ID 'zoomimg' on the tag for it to work, and overflow:hidden on the #container . Also ditch that display:table and display:table-cell they're useless now that we center with Javascript. Also, pressing the down arrow key will cause the container to scroll down, so you should use other keys, as the arrows are reserved by the browser for scrolling the viewport.

JavaScript - Get Browser Height

I am looking for a code snippet to get the height of the viewable area within a browser window.
I had this code, however it is somewhat bugged as if the the body doesn't exceed the height the of the window then it comes back short.
document.body.clientHeight;
I have tried a couple of other things but they either return NaN or the same height as the above.
Does anyone know how to get the real height of the browsing window?
You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
So that's innerHeight for modern browsers, documentElement.clientHeight for IE, body.clientHeight for deprecated/quirks.
Try using jquery:
window_size = $(window).height();
You can use the window.innerHeight
The way that I like to do it is like this with a ternary assignment.
var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;
I might point out that, if you run this in the global context that from that point on you could use window.height and window.width.
Works on IE and other browsers as far as I know (I have only tested it on IE11).
Super clean and, if I am not mistaken, efficient.
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
This should works too. First create an absolute <div> element with absolute position and 100% height:
<div id="h" style="position:absolute;top:0;bottom:0;"></div>
Then, get the window height from that element via offsetHeight
var winHeight = document.getElementById('h').offsetHeight;
Update:
function getBrowserSize() {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.width = '100%';
div.style.height = '100%';
document.documentElement.appendChild(div);
var results = {
width: div.offsetWidth,
height: div.offsetHeight
};
div.parentNode.removeChild(div); // remove the `div`
return results;
}
console.log(getBrowserSize());
var winWidth = window.screen.width;
var winHeight = window.screen.height;
document.write(winWidth, winHeight);
With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;
$('#YourModal').on('show.bs.modal', function () {
$('.modal-body').css('height', $(window).innerHeight() * 0.7);
});
I prefer the way I just figured out... No JS... 100% HTML & CSS:
(Will center it perfectly in the middle, regardless of the content size.
HTML FILE
<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>
CSS FILE
#container{
border:0;
width:100%;
height:100%;
}
#centerpiece{
vertical-align:middle;
text-align:center;
}
for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.
JavaScript version in case if jQuery is not an option:
window.screen.availHeight

Categories

Resources