I'm still an amateur when it comes to JS, I would like to get the height of the browser window, and then get it to update on resize. Is this possible? (code below)
$(document).ready(function() {
var winHeight = $(window).height(),
winWidth = $(window).width();
$('#wrap_project_horizontal_gallery').css({
'height' : winHeight - 170
});
});
I've thought about using setInterval but there must be a better way. Thanks very much for the help
EDIT: This needs to happen without a page refresh
You could bind a method to the resize event in the window and recalculate your variables there, or resize the elements that need resizing.
$(document).ready(function(){
$(window).resize(function() {
// your code here
});
});
or using a handler
$(document).ready(function(){
$(window).resize(handle_window_resize);
});
function handle_window_resize() {
// your code here
}
You can use the jQuery .resize() method.
$(window).resize(function() {
var winHeight = $(window).height(),
winWidth = $(window).width();
$('#wrap_project_horizontal_gallery').css({
'height' : winHeight - 170
});
});
Related
Full jsbin here
Basically, I have a "panel" that is anchored on the right side of the viewport. I want it to be resizable horizontally. The catch is, I want the negative space to be limited between 200px and 400px. If that doesn't make sense, please see the JSBin and it should be easier to understand.
Here's what I have so far:
$( document ).ready(function() {
var maxContentWidth;
var minContentWidth;
$(window).resize(function() {
var ww = $(window).width();
maxContentWidth = ww - 200;
minContentWidth = ww - 400;
$('#content').resizable("option","maxWidth",maxContentWidth);
$('#content').resizable("option","minWidth",minContentWidth);
//if I could even "reinitialize" the pane upon resize, but this doesn't work:
/*$('#content')
.css('right','10px')
.css('top','10px')
.css('left','200px')
.css('bottom','10px');
*/
//I discovered that doesn't work because jquery resizable applies a local "style" attribute, so then I tried this:
//$('#content').attr('style',''); //this makes it completely not resizable at all
});
$('#content').resizable({
handles: "w",
maxWidth: maxContentWidth,
minWidth: minContentWidth
});
});
update: As you can see in the jsbin comments, I decided just reinitializing the panel on window resize was fine and should be simple to do, right? Well, jquery resizable uses a local "style" attribute instead of modifying css. So, I tried just clearing out the style attribute on window.resize, but if I do that I can't resize the panel at all, which doesn't make sense to me.
So. Any ideas how I can "clear" all the styling and reset the CSS without breaking the resizable functionality?
I don't know if i understand, but let's give a try!
http://jsfiddle.net/2eor05dt/
$( document ).ready(function() {
// First Value
var maxContentWidth;
var minContentWidth;
maxContentWidth = $(window).width() - 200;
minContentWidth = $(window).width() - 400;
$(window).resize(function() {
var ww = $(window).width();
maxContentWidth = ww - 200;
minContentWidth = ww - 400;
$('#content').resizable("option","maxWidth",maxContentWidth);
$('#content').resizable("option","minWidth",minContentWidth);
var gap = ww - $('#content').width() - parseInt($('#content').css('left')) - 10;
$('#content').width($('#content').width() + gap);
});
$('#content').resizable({
handles: "w",
maxWidth: maxContentWidth,
minWidth: minContentWidth
});
});
Is there any way to get the browser width and height after a user has resized the window. For example if the window is 1920 by 1080 and the user changes the window to 500 by 500 is there any way to get those two new values in JavaScript or jquery?
Pure Javascript answer:
var onresize = function() {
//your code here
//this is just an example
width = document.body.clientWidth;
height = document.body.clientHeight;
}
window.addEventListener("resize", onresize);
This works fine on chrome. However, it works only on chrome. A slightly more cross-browser example is using the event target properties "outerWidth" and "outerHeight", since in this case the event "target" is the window itself. The code would be like this
var onresize = function(e) {
//note i need to pass the event as an argument to the function
width = e.target.outerWidth;
height = e.target.outerHeight;
}
window.addEventListener("resize", onresize);
This works fine in firefox and chrome
Hope it helps :)
Edit: Tested in ie9 and this worked too :)
If you need to know these values to do layout adjustments, I bet you plan on listening to those values. I recommended using the Window.matchmedia() API for that purpose instead.
It is much more performant and is basically the JS equivalent of CSS media queries.
Very quick example of use:
if (window.matchMedia("(max-width: 500px)").matches) {
/* the viewport is less than or exactly 500 pixels wide */
} else {
/* the viewport is more than 500 pixels wide */
}
You can also setup a listener that'll get called every time the state of the matches property changes.
See MDN for description and example of using a listener.
It's possible by listening to resize event.
$(window).resize(function() {
var width = $(window).width();
var height = $(window).height();
})
You can use the JQuery resize() function. Also make sure you add the same resize logic to reload event. If user reloads in the sized window your logic won't work.
$(window).resize(function() {
$windowWidth = $(window).width();
$windowHeight = $(window).height();
});
$(document).ready(function() {
//same logic that you use in the resize...
});
Practically, I use this and it helps me a lot:
var TO = false;
var resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize';
$(window).bind(resizeEvent, function() {
TO && clearTimeout(TO);
TO = setTimeout(resizeBody, 200);
});
function resizeBody(){
var height = window.innerHeight || $(window).height();
var width = window.innerWidth || $(window).width();
alert(height);
alert(width);
}
You can use the resize event, along with the height() and width() properties
$(window).resize(function(){
var height = $(window).height();
var width = $(window).width();
});
See some more examples here
Use jQuery resize method to listen window size change . inside callback you can get height and width.
$(window).resize(function(){
var width = $(window).width();
var height = $(window).height();
});
Simplest way to get real width and height of an element after window resize as the follow:
<div id="myContainer">
<!--Some Tages ... -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$(window).resize(function () {
//The below two lines of codes more Important to clear the previous settings to get the current measure of width and height
$('#myContainer').css('height', 'unset');
$('#myContainer').css('width', 'unset');
var element = $('#myContainer');
var height = element.height();
var width = element.width();
//Below two lines will includes padding but not border
var innerHeight = element.innerHeight();
var innerWidth = element.innerWidth();
//Below two lines will includes padding, border but no margin
var outerHeight = element.outerHeight();
var outerWidth = element.outerWidth();
//Below two lines will includes padding, border and margin
var outerHeight = element.outerHeight(true);
var outerWidth = element.outerWidth(true);
});
});
</script>
You can use the event object to get the height and width, I use destructuring assignment and the target points to window:
const handleGetDim = ({ target }) => ({
width: target.innerWidth,
height: target.innerHeight,
});
window.addEventListener('resize', handleGetDim);
I am trying to have a container div resize based on the dimensions of the window. The height to width ratio is the most important aspect here and I want to maximize the size of the container in whichever direction (height or width) that is most constraining given the ratio. I have tried a few things unsuccessfully with this being the most recent:
$(window).load(function() {
var h = $(window).height();
var w = $(window).width();
If((h/w)>0.61){
$('#container').css({'height': h, 'width':h*1.64}); }
else{ $('#container').css({'height': w/1.64, 'width':w}); }
})
What do I need to change to get the window to resize? Is there a better way to approach this?
Thanks in advance for any assistance. I am not at all familiar with javascript/JQuery and have been unable to find any useful info... this thing is driving me nuts...
You want to capture the resize event, so assuming your current code works to your likings
$(document).ready(function() {
$(window).resize(function() {
var h = $(window).height();
var w = $(window).width();
if((h/w)>0.61) {
$('#container').css({'height': h, 'width':h*1.64});
}
else {
$('#container').css({'height': w/1.64, 'width':w});
}
});
});
And let's avoid the capital I on the if
I typically use this:
function resize () {
var w = $(window);
var containerWrap = $('#container-wrap');
containerWrap.css({ width:w.width(), height:w.height()});
}
I'm not sure if that answers your ratio question.
EDIT:
This may be more helpful:
$(document).ready(function () {
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize',function() {
missionWrap.css({ width:w.width(), height:w.height()});
});
});
<img src="logo.jpg" class="myImage" alt="Logotyp" />
This is my javascript code:
$(function() {
var windowWidth = $(window).width();
if (windowWidth <= 480) {
$(".myImage").attr("src", "load.jpg");
}
});
The image logo.jpg becomes load.jpg when window width = 480. Works fine. But I want an onClick-function that says when you click load.jpg it becomes logo.jpg again. Can't seem to make it work. Suggestions?
$(".myImage").click(function(){
$(this).attr("src"," logo.jpg");
});
jsBin demo
You can:
create a var windowWidth
create a function "changeImg()" that will handle transformations depending on the windowWidth var value.
Than we use our function changeImg() wherever we want: we can do it also inside a $(window).resize() so the changes will be applied on manual re-size too.
Than on click we play dirty, we fool the windowWidth setting a huge number and call our changeImg function. Fun.
jQuery:
$(function() {
var windowWidth = $(window).width();
function changeImg(){
if (windowWidth <= 480) {
$(".myImage").attr("src", "http://www.rockettheme.com/distribution/download/file.php?avatar=63759_1251026504.jpg");
}else{
$(".myImage").attr("src", "http://screenshots.en.sftcdn.net/blog/en/2009/12/2t_firefox-logo.jpg");
}
}
changeImg();
$(window).resize(function(){
windowWidth = $(window).width(); // grab width while resizeing
changeImg();
});
$('img[alt=Logotyp]').on('click', function(){
windowWidth = 9876; // we fool the windowWidth
changeImg(); // we play dead and call our function :D
});
});
function myAlert() { alert("heelo wrold") };
$(.myImage).setAttribute ("onclick", "myAlert()");
Haven't tried this, but it seems right. ~Ben
I just ran into the weirdest of bugs today. I'm not sure if it's a bug in Chrome or something that I can work around but here goes.
I built a JQuery function to resize a set of images that are posted on a forum:
$(".post-message img.post-image").load(function(){
$(this).each(function() {
var maxWidth = 200;
if($(this).width() > maxWidth)
{
var factor = $(this).width() / maxWidth;
var width = $(this).width();
var height = $(this).height();
$(this).css('width', width / factor);
$(this).css('height', height / factor);
}
});
});
The problem is that this only seems to work when I refresh the page. It doesn't work when you press previous or when you get linked to the page.
In chrome the $(img).width() property returns 0 in both cases when the function doesn't work.
This function performs as expected in IE9 and FF3
What can I do to fix this odd behavior?
Most probably because the images are being pulled up from the browser cache, and the load event is not triggering. The way around this is to manually trigger load if the images's complete properties have been set:
$(".post-message img.post-image").one("load", function(){
$(this).each(function() {
var maxWidth = 200;
if($(this).width() > maxWidth)
{
var factor = $(this).width() / maxWidth;
var width = $(this).width();
var height = $(this).height();
$(this).css('width', width / factor);
$(this).css('height', height / factor);
}
});
}).each(function() {
if(this.complete) $(this).trigger("load");
});
Karmin is correct here. I ran into this problem a few years ago and ended up just not relying on img.load. His workaround for manually triggering the load event should work.
However...
Developers should do max-width or height in CSS in this scenario. In fact, it is good programming practice to do what one can in CSS before doing them in javascript.
Additionally, if one were to keep going with this solution, var width and var height should be placed outside of the if statement next to var maxWidth, and used wherever $(this).width() is called (including the initial check on line 4). Right now the code is unnecessarily creating a new jQuery object to get the height each time when it should have stored and used the value from the first check.
Thanks for the contributions guys. A previous answer given on stack - that I apparently couldn't find this afternoon jQuery && Google Chrome - solved my problem!
$(window).load(function() {
$(".post-message img.post-image").one("load", function(){
$(this).each(function() {
var maxWidth = 200;
if($(this).width() > maxWidth)
{
var factor = $(this).width() / maxWidth;
var width = $(this).width();
var height = $(this).height();
$(this).css('width', width / factor);
$(this).css('height', height / factor);
}
console.log($(this).width())
});
}).each(function() {
if(this.complete) $(this).trigger("load");
});
});
The code has to be executed on $(window).load() together with the provided code by karim79.