Window width and resize - javascript

I would like to calculate the number of icons e.g. 50px depending on the width of the window for a menu.
So I started with:
$(window).width();
While loading the page with document ready function the width will be given. OK!
Now I would calculate the right amount of icons while resize the window.
$(window).resize(function() {
//resize just happened, pixels changed
});
Tasks
Initial width of the window -> if user is not resizing the window
Variable width of the window -> if user is resizing the window
Each task is running but i donĀ“t get it together.
Can u help me --> THX!!
How can i calculate the number of icons with an initial width of the window and while resizing the window?
My Start:
var activeItemcount;
checkWidth();
$(window).resize(checkWidth);
function checkWidth() {
windowSize = $(window).width();
// console.log(windowSize);
var activeItemWidth = '100'; // width of the icons
var maxWidth = windowSize; // max div width on screen
activeItemcount = maxWidth / activeItemWidth; // max icon with actual screen width
activeItemcount = Math.round(activeItemcount) -1; // calculation
console.log(activeItemcount);
var i = '0';
$('.platform-view').each(function(){
if(i < activeItemcount ){
$(this).wrapAll('<div class="iconview-1" />');
i++;
}else{
$(this).wrapAll('<div class="iconview-2" />');
}
});
};

I didn't get you clearly.
but this code will return the variable width of the windows while resizing.
Jquery:
$(window).resize(function() {
$('#log').append('<div>'+$(window).width()+'</div>');
});
HTML:
Example:
A sample of the code

Place your calculation into its own function:
function calculateIcons()
{
var viewport = { width: $(window).width(), height: $(window).height() };
// Do cool things with viewport.width
}
And then you can simply bind this function to the DOMReady and resize functions in jQuery as follows:
$(calculateIcons);
$(window).resize(calculateIcons);

Related

What is a good way to make an event occur when the page has loaded OR on each resize?

I need a query to check the viewport width each time the document is ready or whenever the viewport gets resized. The reason is that I want the main navigation to look and behave differently for different viewport widths.
//EventListener to get viewport width on load
window.addEventListener("load", function () {
window.loaded = true;
});
//get Window Size on Resize
var width = $(window).width();
$(window).on('resize', function reportWindowSize() {
if ($(this).width() != width) {
width = $(this).width();
console.log(width);
}
});
Then I think I need a query like this:
If (page loaded OR viewport width changes) {
if (viewport width > x) {
do things
} else if (viewport width < x) {
do other things
}
};
What would be a good way to form If (page loaded OR viewport width changes) into a JavaScript or jQuery expression?
As Terry pointed out in his comment, you can create a function and reuse it in each of the scenarios that you need it.
I.E.
function checkWidth() {
let windowWidth = $(window).width();
let maxWidth = 1000;
if(windowWidth < maxWidth) {
// do your stuff
}
}
$(document).ready(function() {
checkWidth();
});
$(window).on('resize', function() {
checkWidth();
});
Another solution would be to use Media Queries inside JS.
You can watch for a media query as you would in CSS with the following code:
if (matchMedia) {
let mq = window.matchMedia("(min-width: 500px)");
mq.addListener(checkWidth);
checkWidth(mq);
}
// media query change
function checkWidth(mq) {
if (mq.matches) {
// do your stuff
}
}
You need to call checkWidth after adding the event listener in order to ensure that it executes when the page is loaded.
I got this example from: https://www.sitepoint.com/javascript-media-queries/

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

jQuery function on window events (load and resize)

I'm not sure how to use the order of the window events load and resize on jQuery to make it work when resizing. The first function is used to get the total width except the scrollbar width, because the CSS is using the device width, but the JS is using the document width.
The second function adds a style when the total screen width is between 768px and 1024px, and it should work when I load the page at any screen, after resizing, etc. I'm doing a lot of tests and I think the problem is about the window events order.
For being more specific about the problems, it doesn't remove the style when I load the page at 900px and I expand it to > 1024px! Or by the contrary, it doesn't add the style when I load the page at 1300px and I shorten the width to 900px.
I think it's 'cause of the load and resize events order, but I'm not totally sure. Or maybe I'm not doing the correct declaration of the variable into the resize.
The code:
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' ] };
}
$(document).ready(function(){
var vpwidth=$(window).width();
$(window).on('resize', function(){
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
I believe the issue is that you're not re-calculating the vpwidth on resize, So the value you got when the page was loaded will be used every time window is resized.
try
$(document).ready(function(){
$(window).on('resize', function(){
var vpwidth=$(window).width(); // get the new value after resize
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
The issue is because you are not recalculating the width (vpwidth) on resize function.
It is initialized and set on page load itself and hence doesn't change when the window is resized causing the style to not be added or removed.
You need to re-assign the value to the variable from within the resize function.
$(window).on('resize', function(){
var vpwidth=$(window).width();
}
Demo Fiddle

jQuery width change detection

Now Solved, thanks
I have see a lot of near answers to my problem with resize(), here is my code:
'larger()' is a layout function that I want to call when screen width regardless of device orientation is >= 501, 'smaller()' is a function that i want to call when the screen width is < 501.
My problem I have is that I don't want these functions to be called when the window.height changes. Note that in my page I am using an accordion in mobile view and if I expand an accordion panel, it adds height to the page, even though the browser window hasn't been re-sized. jQuery sees this as a window.resize.
$(window).resize(function(e) {
var winWidth = $(window).width();
if (winWidth >= 501){
larger();
}
if (winWidth < 501){
smaller();
}
});
any answers appreciated, and let me know if I need to clarify anything.
I am using jquery-1.11.0.min.js with jquery-ui-1.10.3.custom.min.js
Thanks
How about storing a reference to the previous width and if the width has changed on resize then call your functions - otherwise skip it. Like So:
// If you don't want it to change the first time
// then set this value on document load to get initial window width
var prevWinWidth = 0;
$(window).resize(function(e) {
var winWidth = $(window).width();
if(winWidth != prevWinWidth) {
if (winWidth >= 501){
larger();
}
if (winWidth < 501){
smaller();
}
prevWinWidth = winWidth;
}
});
Create a global variable that keeps track of the last known width of the window. Only if the width is changing, evaluate the width to call the appropriate function.
var lastWidth = 0;
$(window).resize(function (e) {
var winWidth = $(window).width();
if (lastWidth !== winWidth) {
winWidth >= 501 ? larger() : smaller();
lastWidth = winWidth;
}
});

jQuery to dynamically resize divs

I'm using the media thumbnails that twitter bootstrap v2.3 has in their CSS library. You can see what I'm working on here.
Here is the jQuery I'm using:
<script>
$(window).load(function () {
var maxHeight = 0;
var divs = jQuery(".thumbnail");
jQuery.each(divs, function () {
var height = jQuery(this).height();
if (maxHeight < height) maxHeight = height;
});
divs.css('min-height', maxHeight + 'px');
});
$(window).resize(function () {
var maxHeight = 0;
var divs = jQuery(".thumbnail");
jQuery.each(divs, function () {
var height = jQuery(this).height();
if (maxHeight < height) maxHeight = height;
});
divs.css('min-height', maxHeight + 'px');
});
</script>
Basically my goal was since each thumbnail had different heights and I wanted them to all be equal heights, this script gives them all the same min-height in CSS on load, and everytime the screen is resized based on whichever thumbnail has the greatest height.
I got all that to work, but now the problem I can't figure out is when you drag the screen to smaller/bigger sizes and the min-height becomes very large, I have no code to decrease the min-height so they thumbnail divs look way too big. Does anyone have any code suggestions for me so the divs will all have equal height, but never get too big?
And if you set the height css property rather than min-height, the solution doesn't work for my original goal because the text paragraphs end up extending outside the divs.
On window resize you can set the min-height of the divs again, like this:-
$( window ).resize(function() {
if($( window ).height() < 300){
$( "div" ).css({min-height: 300px});
} else {
$( "div" ).css({min-height: 600px});
}
});

Categories

Resources