Get constant browser height and width - javascript

I was wondering how I could constantly get the current browser's height and width. Right now, I am using jQuery and have something like this:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors. How should I be checking the dimensions at all times? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!). Please let me know what I can do!! Thanks!

Use a window.onresize function as well as a window.onload handler to update the width and height variables.
(Resizeable Demo)
var width,height;
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
Using jQuery objects it would look like this.
(Resizeable Demo)
var width,height;
$(window).on('load resize', function() {
width = this.innerWidth; // `this` points to the DOM object, not the jQuery object
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Try this:
$(window).on("resize",function(){
console.log($(this).height() + " " + $(this).width());
});
fiddle

Try this
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use
window.resizeTo(width, height);
You can trigger the resize function using:
$( window ).resize(function() {
//....
});
Hope it helps you

You can use this to detect a change in screen size:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height and width were declared in a scope that the function has access to. Otherwise make sure to place var before each variable.

Related

Change height of element on resize

Hello guys I'm trying to change height of my element dynamically.
These are my variables.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.
$( window ).bind("resize", function(){
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.
You need to measure the current width of the window on every resize event, since it's changing too.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
$( window ).bind("resize", function(){
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
You need to get windowWidth each time resize event called
And you should add debounce into resize event for better performance.
I often do like this, maybe you can search any better way:
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
// Run code here, resizing has "stopped"
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
}, 250);
});
and I created this to test, you can try it. Btw i increase from 6 to 600 to check easier :D
https://codepen.io/huytran0605/pen/NgBEVO

how to get html content width not window's width

I want to retrieve the html content width. Suppose when we resize the window to smaller size then scrollbar comes, so I want to get the width of the entire html content content that is visible and also the content the that is not visible due to the vertical scrollbar.
You can use window.outerWidth and window.innerWidth.
You may try this:-
var width = document.getElementById('foo').offsetWidth;
Try this code:
window.moveTo(0,0);
window.resizeTo(screen.width,screen.height);
var navButtonsEtcHeight = screen.height - window.innerHeight;
var navButtonsEtcWidth = screen.width - window.innerWidth;
Here's a Fiddle
<div></div>
$(function() {
var dWth = $(document).innerWidth(),
dHgt = $(document).innerHeight();
$('div').append('<h2>'+dWth+'px X '+dHgt+'px</h2>');
$(window).resize(function() {
var dWth = $(document).innerWidth(),
dHgt = $(document).innerHeight();
$('div').html('<h2>'+dWth+'px X '+dHgt+'px</h2>');
});
});
$(window).width(); // Returns width of browser viewport
$(document).width(); // Returns width of HTML document
You want the Element.clientWidth property. It gives the content width of the element.
Here's the documentation: https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements

I get $(image).width() == 0 even when placed inside $(window).load

I want to resize images that are bigger than the window, but I keep getting 0 width and height when I try to get the image size. I read somewhere that it could be because images aren't necessarily loaded at (document).ready so image functions should go under (window).load, but it's no use. I'm a real newbie when it comes to jquery and javascript so I could be doing something wrong.
This is how my javascript file looks:
//<!--
$(document).ready(function(){
...
});
$(window).load(function () {
$(".lightbox img").each(function() {
var width = $(this).width();
var max_width = $(window).width()-30;
var height = $(this).height();
var max_height = $(window).height()-30;
if(width > max_width || height > max_height) {
if(height > width) {
height = max_height;
width = Math.ceil(width / height * max_height);
} else {
width = max_width;
height = Math.ceil(height / width * max_width);
}
}
$(this).attr("width",width);
$(this).attr("height",height);
});
});
//-->
Thanks in advance.
Take a look at this project that provides a callback when images have loaded.
Another reason you could be getting no dimensions is an invisible element (parent or self).
Try $(this).css("width") instead of attr
When the window loads, the images haven't necessarily loaded yet. JavaScript can't get an image's dimensions until is has completely loaded, and until then, you get a computed value of zero.
Bearing this in mind, a repeating loop might help. (Warning: haven't tested)
var width = 0;
while (!width) {
width = $(this).width();
}
Watch out for infinite loops, though.

Continuously check page (client) height and change footer height according to that value

At my website, I try to accomplish (with javascript) that the footer height changes if the page height is larger then a specific value (907 pixels, the body height). It also needs to change if the page height changes (so if the viewer changes his client height).
I use jQuery to get the page height, but I need it's continuously checked, and not only when the page loads.
This is the snippet I use:
$(document).ready(function(){
var windowheight = $(window).height();
if(windowheight >= "907") {
var extrafooterheight = windowheight - 907;
$('#footer').height(40 + extrafooterheight);
$('body').height(907 + extrafooterheight);
}
});
Thanks for your help.
I suggest attaching to the resize event of the window using jQuery:
$(document).ready(function(){
$(window).resize(function() {
var windowheight = $(window).height();
if(windowheight >= "907") {
var extrafooterheight = windowheight - 907;
$('#footer').height(40 + extrafooterheight);
$('body').height(907 + extrafooterheight);
}
});
});
Take a look at the jQuery resize() docs.

Check block visibility

We have code like:
<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>
Text can fit in current browser visible part or not.
How to detect, does the block is in visible part of browser window?
I mean, if resoution is 1024x768 and .block height bigger than 768, then .end is invisible.
we should detect this on window.ready and also on browser window change.
if block is visible, then run some function.
Any help is appreciated.
Something like this:
$.fn.viewport = (function() {
var vp = function(el, opts){
this.el = $(el);
this.opts = opts;
this.bind(); // bind resize and scroll
this.change(); // init change
};
vp.prototype = {
bind: function(){
$(window).bind('resize scroll',
$.proxy(this.change, this));
},
change: function(e){
var p = this.el.position(),
o = this.el.offset(),
d = { w: this.el.width() +o.left, h: this.el.height()+o.top },
win = $(window),
winD = {w:win.width() + win.scrollLeft(), h:win.height()+win.scrollTop()};
if(d.w <= winD.w && d.h <= winD.h){
console.log('inview');
} else {
console.log('out of view');
this.opts.outOfView.call(this);
}
}
};
return function(opts){
return $(this).each(function(){
$(this).data('vp', new vp(this, opts));
});
};
})();
And use like this:
$('#el').viewport({
outOfView: function(){
alert('out of view');
}
});
First grab the window dimensions.
var windowSize = {width: $(window).width(), height: $(window).height() + $(window).scrollTop()};
Next grab the div position in relation to the document:
var position = $('.block').offset()
Then make your if's:
if(position.top > windowSize.height){ /* here we go */ }
You might want to also grab div dimensions in case there is a possibility it will be out of bounds on the top or left side.
You could make it into a function that returns a boolean value and then call it on the window.resize and document.ready events.
EDIT: Added scrollTop to account for scrolling.
As a quick answer you'll have to do some computation on load (psuedocode assumes jQuery).
Find the window height $(window).outerHeight(true)
Find the offset of the ".end" element $(".end").offset()
Find the scroll distance of the window $(window).scrollTop()
Calculate! It should roughly be:
if ((step1 + step3) > step2) {
//do stuff here
}
Note that that does not check if you are scrolled past the ".end" element. I didn't verify this one, so hopefully I'm not missing something big.
Get the offsetTop and offsetLeft attributes of the element
Get the width of the element in question
Get the width of screen
Do the relevant maths and see if the element is in the viewport or now.
in jQuery you can do something like
$("#element").attr("offsetTop")
EDIT:
Simple and Effective: http://jsfiddle.net/hPjbh/

Categories

Resources