I have this code from website
jQuery refresh page on browser resize
Works fine but its too sensitive on mobile devices.
So i shoud add some margin of error.
How tu use this code when difference in browser width is more than 100px
if browser width is smaller and larger
//refresh page on browser resize
$(window).bind('resize', function(e)
{
if (window.RT) clearTimeout(window.RT);
window.RT = setTimeout(function()
{
this.location.reload(false); /* false to get page from cache */
}, 200);
});
I'm assuming that by "when difference in browser width is more than 100px" means you're attempting to detect that the window has changed in size by more than 100px. To do this you'll need to store the original width of the window and compare against that:
var originalWidth = $(window).width();
$(window).bind('resize', function(e) {
if (window.RT) clearTimeout(window.RT);
window.RT = setTimeout(function() {
if (Math.abs($(window).width() - originalWidth) > 100) {
this.location.reload(false); /* false to get page from cache */
}
}, 200);
});
(This seems an odd requirement, however: refreshing the page on window resize is far from ideal UX. You may find it better to use CSS breakpoints, or scripting if necessary, to modify the page in place rather than the brute-force approach of reloading the whole thing.)
Store
var currentWidth = $( window ).width() to a temporary variable.
After resizing, check the difference
( currentWidth - $(window).width() ) > 100
let currentWidth = $(window).width();
$(window).on('resize', function(){
if(($(window).width() - currentWidth ) > 100 || (currentWidth - $(window).width()) > 100 ) {
currentWidth = $(this).width();
location.reload();
}
});
I made a little script to change the height of a group of li-elements to the one with the most content.
The code works fine, but it should also work by resizing the browser width.
I need to know why it doesn't reload by changing the browser width ?
Here is my Code :
//changes slider hight to the hight of the li with the most content
function heightChange() {
var max = -1;
$(".feedback li").each(function() {
var h = $(this).height();
max = h > max ? h : max;
});
$(".feedback li").css("height", max);
};
// start by open site
heightChange();
// load function by resizing of the browser window
$(window).bind("resize", function(){
heightChange();
});
You need to reset your height before setting it again. Demo
$(window).on("resize", function(){
$(".feedback li").css("height", "auto");
heightChange();
});
Otherwise will height() just return the specified value;
Also, .on() is the preferred way to bind and event, as of jQuery 1.7
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;
}
});
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);
As you are aware, in Internet Explorer, the window.resize event is fired when any element on the page is resized. It does not matter whether the page element is resized through assigning/changing its height or style attribute, by simply adding a child element to it, or whatever -- even though the element resizing does not affect the dimensions of the viewport itself.
In my application, this is causing a nasty recursion, since in my window.resize handler I am resizing some <li> elements, which in turn re-fires window.resize, etc. Again, this is only a problem in IE.
Is there any way to prevent window.resize from firing in IE in response to elements on the page being resized?
I should also mention that I'm using jQuery.
I just discovered another problem which might help you.
I am using jQuery and I have window.resize event to call a function which will re-position the div appended to the body.
Now when I set the LEFT css property of that appended div, the window.resize event get trigger for NO GOOD REASON.
It results in an infinite loop, triggering the window.resize again and again.
The code without fix:
$(window).resize(function(){
var onResize = function(){
//The method which alter some css properties triggers
//window.resize again and it ends in an infinite loop
someMethod();
}
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(onResize, 10);
});
Solution:
var winWidth = $(window).width(),
winHeight = $(window).height();
$(window).resize(function(){
var onResize = function(){
//The method which alter some css properties triggers
//window.resize again and it ends in an infinite loop
someMethod();
}
//New height and width
var winNewWidth = $(window).width(),
winNewHeight = $(window).height();
// compare the new height and width with old one
if(winWidth!=winNewWidth || winHeight!=winNewHeight){
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(onResize, 10);
}
//Update the width and height
winWidth = winNewWidth;
winHeight = winNewHeight;
});
So basically it will check if the height or width is changed (which will happen ONLY when you actually resize with window).
this made sense to me and seems to work in IE7 and above:
//variables to confirm window height and width
var lastWindowHeight = $(window).height();
var lastWindowWidth = $(window).width();
$(window).resize(function() {
//confirm window was actually resized
if($(window).height()!=lastWindowHeight || $(window).width()!=lastWindowWidth){
//set this windows size
lastWindowHeight = $(window).height();
lastWindowWidth = $(window).width();
//call my function
myfunction();
}
});
Bind your resize listener with .one() so that it unbinds itself after firing. Then you can do anything you want, so long as at the end you rebind the resize listener. I found the easiest way to do this is by putting the resize listener in an anonymous function like so:
var resizeListener = function(){
$(window).one("resize",function(){ //unbinds itself every time it fires
//resize things
setTimeout(resizeListener,100); //rebinds itself after 100ms
});
}
resizeListener();
You don't technically need the setTimeout wrapped around the resizeListener() but I'd threw it in there as a just-in-case and for some extra throttling.
I solved it by unbinding the resize function, rebuilding the page and then binding the resize function again:
function rebuild() {
$(window).unbind('resize');
/* do stuff here */
$(window).bind('resize',rebuild);
}
$(window).bind('resize',rebuild);
EDIT
Bind and unbind don't go well with IE8. Though Microsoft even gave up on IE8 you might want to try this (untested!):
function rebuild(){
if(!window.resizing) return false;
window.resizing=true;
/* do stuff here */
window.resizing=false;
}
window.resizing=false;
document.body.onresize=rebuild;
#AamirAfridi.com's answer solved my problem.
It's a good idea to write a common function to solve such stuff:
function onWindowResize(callback) {
var width = $(window).width(),
height = $(window).height();
$(window).resize(function() {
var newWidth = $(window).width(),
newHeight = $(window).height();
if (newWidth !== width || newHeight !== height) {
width = newWidth;
height = newHeight;
callback();
}
});
}
Use it like this, and you don't have to worry about the different behavior in IE any more:
onWindowResize(function() {
// do something
});
I ran into this problem today and decided to put the following at the top of my global included javascript file:
var savedHeight = 0;
var savedWidth = 0;
Event.observe(window, 'resize', function (e) {
if (window.innerHeight == savedHeight &&
window.innerWidth == savedWidth) { e.stop(); }
savedHeight = window.innerHeight;
savedWidth = window.innerWidth;
});
That requires Prototype, by the way.
A mix of the unbind / bind method with a delayed call.
It works in Internet Explorer 8 and below, preventing evil loop and hangs on versions 6 and 7.
function resizeViewport()
{
// Unbind and rebind only for IE < 9
var isOldIE = document.all && !document.getElementsByClassName;
if( isOldIE )
$(window).unbind( 'resize', resizeViewport );
// ...
if( isOldIE )
{
setTimeout(function(){
$(window).resize( resizeViewport );
}, 100);
}
}
$(window).resize( resizeViewport );
You can try this:
Constructor:
this.clientWidth = null;
this.clientHeight = null;
Some function:
var clientWidth = window.innerWidth || document.documentElement.clientWidth;
var clientHeight = window.innerHeight || document.documentElement.clientHeight;
if (clientWidth != this.clientWidth || clientHeight != this.clientHeight ) {
this.clientWidth = clientWidth;
this.clientHeight = clientHeight;
... YOUR CODE ...
}
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
window.innerHeight - the inner height of the browser window
window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
document.documentElement.clientHeight
document.documentElement.clientWidth
or
document.body.clientHeight
document.body.clientWidth
(function ($){
//if ie8 -> return;
var lastHeight = 0;
var lastWidth = 0;
$(window).resize(function(event){
if (window.innerHeight == lastHeight && window.innerWidth == lastWidth)
{ event.stopImmediatePropagation(); }
lastHeight = window.innerHeight;
lastHeight = window.innerWidth;
});
})();
does the trick for me...
<pre>
var cont = 0;
var tmRsize = 100;
var lastWindowWidth = $(window).width();
var lastWindowHeight = $(window).height();
/*****redimensionamiento**********/
$(window).resize(function()
{
if($(window).width() != lastWindowWidth || $(window).height() != lastWindowHeight)
{
clearTimeout(this.id);
this.tiempo = tmRsize;
this.id = setTimeout(doResize, this.tiempo);
}
});
function doResize()
{
lastWindowWidth = $(window).width();
lastWindowHeight = $(window).height();
$('#destino_1').html(cont++);
}
Here's how i deal with finding out if the resize event was fired by an element or by really resizing the window:
If the event's target.nodeType doesn't exist, it is most likely the window, as any other element on the page would have a nodeType.
So here's the pseudo-code (using jQuery) with the added check:
$(window).resize(function(event){
if ( $(event.target.nodeType).length == 0 ){
// Anything here is run when the window was resized
// not executed when an element triggered the resize
}
});
I couldn't get the resize event to fire when an element resized (only tried in IE8 though).
However what is the target on the event object when you're experiencing this issue, could you do:
$(window).resize(function(e) {
if( e.target != window ) return;
// your stuff here
});
My patch:
<!--[if lte IE 7]>
<script type="text/javascript">
window.onresize = null; // patch to prevent infinite loop in IE6 and IE7
</script>
<![endif]-->
It is up to the how contents are on the resize event.
I figured out the above solves only when a page consists of static contents, not dynamically rendered ones.
In the dynamic case where the existing contents will be re-rendered by some trigger event like a contents reload function, we need to use $(document).width() or $(document).height() instead.
This is because of scroll bar of the window.
If a page has the scroll bar and the main contents will be re-rendered by clicking a button “Reload”, the scroll bar disappears on the event.
In that case, $(window).width() or $(window).height() is changed by the contents rendering, not by the actual window resizing.
$(window).resize(function(event)
{
if (typeof event.target.tagName == 'undefined')
{
// ...
}
});