Cross-browser window resize event - JavaScript / jQuery - javascript

What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?
And can you turn both scrollbars on/off?

jQuery has a built-in method for this:
$(window).resize(function () { /* do something */ });
For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:
function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});

$(window).bind('resize', function () {
alert('resize');
});

Here is the non-jQuery way of tapping into the resize event:
window.addEventListener('resize', function(event){
// do stuff here
});
It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.

Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:
function foo(){....};
window.onresize=foo;

Since you are open to jQuery, this plugin seems to do the trick.

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
while this worked in both browsers:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

jQuery provides $(window).resize() function by default:
<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
$rightPanelData = $( '.rightPanelData' )
$leftPanelData = $( '.leftPanelData' );
//jQuery window resize call/event
$window.resize(function resizeScreen() {
// console.log('window is resizing');
// here I am resizing my div class height
$rightPanelData.css( 'height', $window.height() - 166 );
$leftPanelData.css ( 'height', $window.height() - 236 );
});
</script>

I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.

I think you should add further control to this:
var disableRes = false;
var refreshWindow = function() {
disableRes = false;
location.reload();
}
var resizeTimer;
if (disableRes == false) {
jQuery(window).resize(function() {
disableRes = true;
clearTimeout(resizeTimer);
resizeTimer = setTimeout(refreshWindow, 1000);
});
}

hope it will help in jQuery
define a function first, if there is an existing function skip to next step.
function someFun() {
//use your code
}
browser resize use like these.
$(window).on('resize', function () {
someFun(); //call your function.
});

Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.
Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
Make sure to check out the demo to see the difference.
Here is the function for completeness.
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});

Related

Javascript function is not working sometimes at certain level

I have this Javascript function for hover items. İt has to work under 958px but its not working. so how can I control that.
But when I resize page up and down, JS stops working.
What's wrong with my function? I am unable to figure it out.
$(document).ready(() => {
if ($(window).width() >958){
$('#group-subscription .owl-item').on('mouseenter', function(){
$(this).nextAll().addClass('has-positive-translate')
$(this).prevAll().addClass('has-negative-translate')
}).on('mouseleave', function() {
removeHasClasses()
})
function removeHasClasses() {
$('#group-subscription .owl-item').removeClass('has-negative-translate has-positive-translate slider-hover-bigger')
}
}
})
Your code is not related to resizing event, it only one time execute when a page is loaded and it is ready, All in all, you should use resize event instead of the ready event.
$(window).on('resize', function(){
var winx = $(this);
if (winx.height() >= 958) {
/* use your code here */
}
});

$(document).ready() & $(function(){}

I have two functions:
function func1(){}
and
function func2(){}
both of these functions requires the following to work
$(document).ready();
$(window).resize();
so I have implemented it to both the functions as follows:
$(document).ready(func1);
$(window).resize(func1);
and
$(document).ready(func2);
$(window).resize(func2);
The problem? there is two;
1) I already have $(function(){ wrapping the above two functions, but I still need need $(document).ready(); why? isn't both the same thing?!
2) I am trying to short-cut the code and only have $(document).ready();"if needed" and $(window).resize(); to appear once and then add functions to it, and not add it to functions. Confused? okay...
so I basically want to do this:
$(document).ready(func1,func2);
$(window).resize(func1,func2);
But it didn't work, any ideas?
My script:
$(function(){
//Prevent clicking on .active & disabled links
'use strict'; $('.active, disabled').click(function(e) {
e.preventDefault();
});
//Off-canvas menu
var $pages = $('#page, #secondHeader'),
$header = $('#header'),
$secondHeader = $('#secondHeader .menu-button');
$secondHeader.on('touchstart click', function(e) {
e.preventDefault();
$pages.toggleClass("pageOpen");
$header.toggleClass("headerOpen");
$(this).toggleClass("menu-button-active");
});
$('#page').on('touchstart click', function() {
$pages.removeClass("pageOpen");
$header.removeClass('headerOpen');
$secondHeader.removeClass("menu-button-active");
});
//Grid system
var gridElement = $(".gridElement", "#grid3");
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
function GalleryGrid() {
var grid3 = $('#grid3');
var width = $(window).width();
if (width < 1024 && width > 770) {
var grid1 = $('#grid1');
var grid2 = $('#grid2');
for (var i = 0; i < gridElement.length; i++) {
if (i < gridElement.length / 2) {
grid1.append(gridElement[i]);
} else {
grid2.append(gridElement[i]);
}
}
} else {
grid3.append(gridElement);
}
}
$(document).ready(fullScreen);
$(window).resize(fullScreen);
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
});
Use a wrapper function to call both functions on the same event:
function go(){
func1(); // Call function 1 and 2.
func2();
}
$(document).ready(go);
$(window).resize(go);
Or, to make absolutely sure the document is ready, you can even attach the resize event listener after the ready event:
$(document).ready(function(){
$(window).resize(go);
});
Do like this.
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
fullScreen();
GalleryGrid();
$(window).resize(function(){
fullScreen();
GalleryGrid();
});
Just call the function like fullScreen() no need to use $(document).ready.
For Gallery Grid
Remove from you code. No need to call (function(){}) twice.
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
I'd suggest using an anonymous function to get this done.
For example:
$(document).ready(function() {
1();
2();
});
That should be a good starting point.
(function(){ ... })();
It is not equivalent to document.ready. Here it is not necessary DOM is ready. It is anonymous function it invoke itself as soon as possible when the browser is interpreting your ecma-/javascript.
Better and suggested to use document.ready():
$(document).ready(function(){
fullScreen();
//other code
});
Don't
Don't call $(document).ready() inside $(document).ready(), it doesn't make sense. The code inside of $(document).ready(/* the code here */) is not executed immediately. It is scheduled for execution sometime later (when the document is ready).
Calling
$(document).ready(function() {
//do this
$(document).ready(some_function)
//do that
});
Is like saying "wait until the document is ready, do this, wait until the document is ready to do some_function, do that."
Document ready event:
$(function(){})
Is just a shortcut/shorthand for:
$(document).ready(function(){})
ready is an event. It belongs to the document object and it is triggered when the document is ready.
To register two functions to be called when the document is ready just do either:
$(document).ready(function() {
func1();
func2();
});
Or
$(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(document).ready(func3);
Or
function func3() {
func1();
func2();
}
$(func3);
Window resize event:
resize is an event. It belongs to the window object and it is triggered when the window is resized.
To register two functions to be called when the window is resized just do:
$(window).resize(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(window).resize(func3);

setTimeout won't execute the function

I even looked at this and this solution still didn't help me : Execute a function after X seconds in jquery
Here is my code:
// featured bounce
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
setTimeout( function(){
$(this).removeClass('bounce');},
1300
);
});
The adding of the class works, but the setTimeout ordeal will not work. It won't even execute and not javascript error is thrown in the Chrome console. I feel like I have everything typed out correctly.. the class on the .animated object after the addClass() looks like this:
"animated bounce"
And the animation plays, but then it NEVER removes the "bounce" from the class attribute.
Any help?
Using Function.prototype.bind correctly, you can avoid cheap context hacks like var that = this.
// featured bounce
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout(elem.removeClass.bind(elem, 'bounce'), 1300);
});
Side Note: Function.prototype.bind is an ES5 addition and browser support needs to be considered. See the compatibility table at the bottom of the MDN article on the function.
The scope of this is pointing at window, not the element you expect.
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout( function(){
elem.removeClass('bounce');},
1300
);
});
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
(function(that) {
setTimeout( function(){
// use `that` instead of `this`
$(that).removeClass('bounce');
}, 1300);
})(this); //pass `this` into this function
});

Remove Scroll Binding Without Removing Others with Jquery

Is there a way to remove the binding below, without removing other bindings on that element that deal with scroll? I tried the unbind('scroll', scrollHandler) and it didnt work also. I have another scroll binding that is removed because of this. Is there a way to do this with a namespace?
var scrollHandler = function () {
// Inner Logic
};
windowElement.unbind('scroll').scroll(scrollHandler);
Fixed it by using this.
windowElement.unbind('scroll.fixedTop').bind('scroll.fixedTop', scrollHandler);
You can use on() and off():
http://jsfiddle.net/STPcy/
var handler1 = function() {
console.log('handler1');
};
var handler2 = function() {
console.log('handler2');
};
$('#myDiv').on('click', handler1);
$('#myDiv').on('click', handler2);
$('#myDiv').off('click', handler1);
This results in only handler2() being called.

Error on jQuery Plugin

I'm using jquery 1.9.1 and I'm trying to develop a plugin. The problem is that the plugin isn't working. Here's the code:
;(function($) {
$.fn.single = function() {
return this.each(function(){
// Get the instance
var element = $(this);
// Resize the "data-target" divs
element.load(function(){
changeCSS(element);
});
// Bind the method to the resize window event
$(window).bind("resize", function(){
changeCSS(element);
});
});
};
// function to resize all the "data-target" divs
function changeCSS(element) {
// Grab the screen resolution
var windowWidth = $(window).width();
var windowHeight = $(window).height();
// Count how many targets the div has
var targetsSize = $("[data-target]").size();
// Resize the parent div
$(element).css({
"width" : windowWidth,
"height": windowHeight * targetsSize
});
// Resize all the targets div
$(element + "> div[data-target]").each(function(){
$(this).css({
"width" : windowWidth,
"height": windowHeight
});
});
}
})(jQuery);
And I'm calling it on the document like that:
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/single-0.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#single").single();
});
</script>
There's no problem in the console. What I'm doing wrong?
I'm assuming that it is because you are misusing the method .load. If you look at the jQuery docs, it is intended for:
.load() : Load data from the server and place the returned HTML
into the matched element.
http://api.jquery.com/load/
Remove the lines element.load(function ..., simply call your changeCSS function, you're already loading this extension on Document.Ready
return this.each(function () {
// ...
changeCSS(element); // <-- just run the function right away
// ... etc
});
Generally it is bad practice to call a function before it is declared. To get your plugin right, you will be better of starting structuring it correctly from the beginning. Besides that, as #mcpDESIGNS point out, you are using the .load method wrongly. Also, it would be useful if you explain what exactly it is you are trying to accomplice here.
To get a good start making jQuery plugins, try to look at the documentation at jQuery here or you can look at this tutorial.
This is the preferred structure:
(function($) {
// Declare your methods at the beginning of your plugin
var yourMethods = {
'methodOne' : function() {
},
'methodTwo' : function() {
}
};
$.fn.pluginName = function() {
return this.each(function() {
});
}
}(jQuery));
Instead of:
element.load(function(){
changeCSS(element);
});
I did:
changeCSS(element);
And... Instead of:
$(element + "> div[data-target]")
I did:
$(element).children('div[data-target]')
And now the plugin is being executed with no bugs or errors.
Thanks Guys!

Categories