Run jQuery script on window resize - javascript

I have a bit of script that will run various functions on a window resize,
$.event.add(window, 'load', resizeFrame);
$.event.add(window, 'resize', resizeFrame);
function resizeFrame(){
// various scripts //
}
This works absolutely fine, and the scripts I run in there work also. I then have a separate script that sets the height of various divs on document load, which also works just fine.
var h = 0,
target = $('.home #content .items-row .item article');
target.each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
target.each(function () {
$(this).css("height", h + 'px');
});
$('.testimonials .items-row').each(function () {
$('.span4 article', this).css('height',
Math.max.apply( Math,
$.map($('.span4 article', this), function(x) {
return $(x).height();
})
)
);
});
However when i try to combine the two, my divs will resize once on load, but not again on window resize. This is how i have combined the two,
function articleResize(){
var h = 0,
target = $('.home #content .items-row .item article');
target.each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
target.each(function () {
$(this).css("height", h + 'px');
});
$('.testimonials .items-row').each(function () {
$('.span4 article', this).css('height',
Math.max.apply( Math,
$.map($('.span4 article', this), function(x) {
return $(x).height();
})
)
);
});
}
$.event.add(window, 'load', resizeFrame);
$.event.add(window, 'resize', resizeFrame);
function resizeFrame(){
articleResize();
}
If anyone has any clues it would be greatly appreciated.
EDIT
as background here is the resizeFrame in its entirety,
function resizeFrame(){
var screenWidth = $(window).width();
function phoneEnable(){
$('#MainNav ul.nav').prependTo('.sidr-inner').addClass('nav-list nav-collapse');
$('#MainSocial ul.roundIcons').prependTo('.sidr-inner');
};
function phoneDisable(){
$('#sidr ul.nav').prependTo('#MainNav').removeClass('nav-list nav-collapse');
$('#sidr ul.roundIcons').prependTo('#MainSocial');
}
if (screenWidth >= 980){
phoneDisable();
} else{
phoneEnable();
};
var highestBox = 0;
$('.blog-featured .item article', this).each(function(){
if($(this).height() > highestBox)
highestBox = $(this).height();
});
$('.blog-featured .item article',this).height(highestBox);
articleResize();
};

Your load event was not firing in the samples I tried.
Instead of your current event registration try this:
JSFiddle: http://jsfiddle.net/j9SR5/1/
// jQuery DOM ready shortcut event handler (with locally scoped $)
jQuery(function($){
// Register for window resize
$(window).resize(resizeFrame);
// Do initial resize
resizeFrame();
});
Update: http://jsfiddle.net/TrueBlueAussie/j9SR5/5/
You are setting a fixed height, so the next time you resize the height is as specified previous (and will not change). The new JSFiddle resets the heights to their natural state first.
// Revert to height based on content
target.each(function () {
$(this).css("height", '');
});

jQuery is just wrapping the standard resize DOM event, eg.
window.onresize = function(event) {
...
};
jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ,

Related

How to re-run this jQuery plugin on window resize?

I have a list where the first-child element is visible on desktop, and is hidden on screens under 767px, and then every other element cycles through on a loop for all screen sizes.
I have been trying to re-run this jQuery plugin on window resize without success, please could someone help implement window resize function?
I have put together an example here
(function ($){
$.fn.extend({
rotaterator: function(options) {
var defaults = {
fadeSpeed: 500,
pauseSpeed: 100,
child:null
};
var options = $.extend(defaults, options);
return this.each(function() {
var o =options;
var obj = $(this);
var obj2 = "ul li:first-child";
var items = $(obj.children(), obj);
var items2 = $(obj.children(), obj2);
if ($(window).width() < 767) {
items.each(function() {$(this).hide();})
items2.each(function() {$(obj2).hide();})
} else {
items.each(function() {$(this).hide();})
items2.each(function() {$(obj2).show();})
}
if(!o.child){var next = $(obj).children(':nth-child(2)');
}else{var next = o.child;
}
$(next).fadeIn(o.fadeSpeed, function() {
$(next).delay(o.pauseSpeed).fadeOut(o.fadeSpeed, function() {
var next = $(this).next();
if (next.length == 0){
next = $(obj).children(':nth-child(2)');
}
$(obj).rotaterator({child : next, fadeSpeed : o.fadeSpeed, pauseSpeed : o.pauseSpeed});
})
});
});
}
});
})(jQuery);
and call
(function ($) {
$('ul').rotaterator({fadeSpeed:5000, pauseSpeed:1000});
})(jQuery);
Thanks for looking.
UPDATE:
I have added window resize, it seems it's had an affect of how it initially loads and performs thereafter, showing all elements first, please see updated fiddle demo
Your current implementation already adapts to the new window size as soon as the fade-out completes and the next call to rotaterator is made.
If however you want an immediate effect at the resize event, so that the animation restarts taking the new window size into account, then use the jQuery stop method to stop any current animations of an ul child element.
For instance:
$(window).resize(function() {
$('ul *').finish();
$('ul').rotaterator({fadeSpeed:5000, pauseSpeed:1000});
});

Fire Function on Window Resize

I have a function that resizes/equalizes elements so that they are the same size. I call that function on DOM Ready and I want to call it on window resize as well, but it doesn't seem to be firing. The console.log fires like you'd expect but not the equalize() function.
// Equalize
var equalize = function(){
var maxHeight = 0;
$('.equalize').each(function(){
if ($(this).outerHeight() > maxHeight) { maxHeight = $(this).outerHeight(); }
});
$('.equalize').outerHeight(maxHeight);
};
jQuery( document ).ready(function( $ ) {
// fire equalize
equalize();
$(window).resize(function(){
equalize();
console.log('[Log] Resized');
}).trigger('resize');
});
Am I missing something here when it comes to firing functions on window resize? Thanks!
For an element to resize so it fits the content, the style overflow : auto has to be set, otherwise the element just keeps it's size and the content overflows.
Also, when you explicitly set the outerHeight, the elements stops auto-resizing to fit the content, the default height of auto has to be applied to trick it into resizing before the elements heights are compared
var equalize = function() {
var max = Math.max.apply(null,
$('.equalize').css('height', 'auto').map(function() {
return $(this).outerHeight();
})
);
$('.equalize').outerHeight(max);
};
jQuery(document).ready(function($) {
$(window).resize(function() {
equalize();
}).trigger('resize');
});
div{
display: inline-block;
position: relative;
width: 50%;
float: left;
background: yellow;
}
.other{
background: salmon;
overflow:auto;
}
FIDDLE
Get rid of the trigger see if that helps. According to jQuery doc the trigger fires an even (calls a function)
I don't think it makes sense to call a function then after the function is called, trigger it again, then that should go on forever....may be the cause of the problem.
// Equalize
var equalize = function(){
var maxHeight = 0;
$('.equalize').each(function(){
if ($(this).outerHeight() > maxHeight) { maxHeight = $(this).outerHeight(); }
});
$('.equalize').outerHeight(maxHeight);
};
jQuery( document ).ready(function( $ ) {
// fire equalize
equalize();
$(window).resize(function(){
equalize();
console.log('[Log] Resized');
}); // got rid of the trigger...not needed
});
It's a little hard to say without some more detail about what's going on in your project, but this works for me (at least to get equalize to fire on window resize):
var equalize = function(){
var maxHeight = 0;
$('.equalize').each(function(){
if ($(this).outerHeight() > maxHeight) { maxHeight = $(this).outerHeight(); }
});
$('.equalize').outerHeight(maxHeight);
};
jQuery( document ).ready(function( $ ) {
equalize();
$(window).resize(function(){
equalize();
console.log('[Log] Resized');
})
});

Return updating variable from function

I'm trying to use javascript/jQuery to find the width of the window and use the variable in a later function.
$(function resizer() {
function doneResizing() {
var windowWidth = $(window).width();
return windowWidth;
}
var getWidth = doneResizing();
var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});
doneResizing();
return getWidth;
});
var finalWidth = resizer()
So the resize function updates whenever the window is resized and windowWidth is updated automatically. When the variable is returned outside of the function, getWidth doesn't update with a window resize unless I refresh the page. Any ideas? I just picked up js/jq 2 weeks ago, and I'm doing my best to wrap my head around returns and closures, so I may have overlooked something here. Thanks.
it would be much simpler to do the following:
var finalWidth;
$( document ).ready(function() {
//Set this the first time
finalWidth = $(window).width();
$(window).resize(function() {
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
});
});
and use finalwidth outside as it is a global variable.
You get the same functionality without the complexity.
Update
As commented, global variables are bad practice ( e.g. also http://dev.opera.com/articles/view/javascript-best-practices/ ).
To avoid a global variable finalWidth can be moved inside document.ready and any necessary functions can be called from inside resize(function() { event handler.
Update 2
Due to the problem with dragging causing multiple resize events, code has been updated.
Reference: JQuery: How to call RESIZE event only once it's FINISHED resizing?
JSFiddle: http://jsfiddle.net/8ATyz/1/
$( document ).ready(function() {
var resizeTimeout;
$(window).resize(function() {
clearTimeout(resizeTimeout);
resizeTimeout= setTimeout(doneResizing, 500);
});
doneResizing(); //trigger resize handling code for initialization
});
function doneResizing()
{
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
}
function anotherFunction(finalWidth)
{
alert("This is anotherFunction:"+finalWidth);
}
You have mixed up your resizer function with the jQuery ready function.
To keep track on the window width you can do
(function ($) {
var windowWidth;
// when the document is fully loaded
$(function(){
// add an resize-event listener to the window
$(window).resize(function(){
// that updates the variable windowWidth
windowWidth = $(window).width();
})
// trigger a resize to initialize windowWidth
.trigger('resize');
// use windowWidth here.
// will be updated on window resize.
});
}(jQuery));

jQuery: Add or Remove function in a specific window size

I am very new to jQuery/JS and I have little problem with add or remove function in a specific window size.
I would appreciate if you can take a look at my code and correct it.
In detail, I use tinyscrollbar plugin that I want only appear in a specific window size(let's say above 650px of window width).
Here is my code:
<!--****preload latest jQuery and tinyscrollbar plugin, then...****-->
<script type="text/javascript">
function newsScroll() {
$("#newsScroll").tinyscrollbar();
};
/*
if windows width is less than 650px, remove newsScroll function and
switch DIV ID to "spNewsScroll" and vice versa.
*/
function scrollOnOff(width) {
width = parseInt(width);
if (width < 650) {
$(window).unbind(newsScroll);
$("#newsScroll").attr('id','spNewsScroll');
} else {
$(window).bind(newsScroll);
$("#spNewsScroll").attr('id','newsScroll');
}
};
$(function() {
//get window size as of now.
scrollOnOff($(this).width());
$(window).resize(function() {
scrollOnOff($(this).width());
});
});
</script>
Try this, tested and working :-)
Live demo: http://jsfiddle.net/oscarj24/fUsnj/21/
function scrollOnOff(width) {
width = parseInt(width);
if(width < 650){
$(window).trigger('newsScroll');
$('#newsScroll').attr('id','spNewsScroll');
} else {
$('.scrollbar').hide();
$('#spNewsScroll').attr('id','newsScroll');
}
};
$(function() {
$(window).bind('newsScroll', function(e) {
$('.scrollbar').show();
$('#newsScroll').tinyscrollbar();
});
var screenWidth = $(this).width();
scrollOnOff(screenWidth);
$(window).on("resize", function(event){
var w = $(this).width();
scrollOnOff(w);
});
});
​

center on resize too

This works:
$.fn.center = function () {
this.css("position", "absolute");
this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
return this
};
$('#container').center();
.. but the element stays in the same position if the window is resized, how do I center it with the resize too?
Thanks
You would need to execute that code in the window resize event. But, if the browser is resized this event fires huge! So it's in general a good idea to create a little "balancer".
$(window).bind('resize', function() {
var that = this;
if(!('balancer' in that) ) {
that.balancer = setTimeout(function() {
$('#container').center();
delete that.balancer;
}, 200);
}
});
This will absorb the many events that are fired when resizing the browser window. In fact, it only calls the .center() at a maximum of 200ms. You probably should even increase that value and cache the node reference to the #container element.
EDIT::
giving percentage to top and left can put at center. but this bad ... really really bad.
$.fn.center = function () {
$(this).css({'position': 'absolute',
'top': '40%',
'left': '40%'
});
};
$(function (){
$('#container').center();
})
On jsfiddle.

Categories