Javascript Custom Resize Event [duplicate] - javascript

This question already has answers here:
How to detect DIV's dimension changed?
(28 answers)
Closed 7 years ago.
I have a very simple question, or at least it seems that way.
I have a DIV element which will be resized at one moment. I want to be able to capture the resizing moment.
Something like this:
function myFunction(){
alert('The DIV was resized');
}
divElement.addEventListener("resize", myFunction, false);
Does anyone know the answer?
Thanks

As of December 2011, there's no built-in event to detect when a div resizes, just when a window resizes.
Check out this related question: Detecting when a div's height changes using jQuery, and this plugin from the solution to that question: http://benalman.com/projects/jquery-resize-plugin/
With jQuery resize event, you can now bind resize event handlers to
elements other than window, for super-awesome-resizing-greatness!
Why is a plugin needed for the resize event?
Long ago, the powers-that-be decided that the resize event would only
fire on the browser’s window object. Unfortunately, that means that if
you want to know when another element has resized, you need to
manually test its width and height, periodically, for changes. While
this plugin doesn’t do anything fancy internally to obviate that
approach, the interface it provides for binding the event is exactly
the same as what’s already there for window.
For all elements, an internal polling loop is started which
periodically checks for element size changes and triggers the event
when appropriate. The polling loop runs only once the event is
actually bound somewhere, and is stopped when all resize events are
unbound.
Sample Code
// You know this one already, right?
$(window).resize(function(e){
// do something when the window resizes
});
// Well, try this on for size!
$("#unicorns").resize(function(e){
// do something when #unicorns element resizes
});
// And of course, you can still use .bind with namespaces!
$("span.rainbows").bind( "resize.rainbows", function(e){
// do something when any span.rainbows element resizes
});

You can try this plugin - http://benalman.com/code/projects/jquery-resize/examples/resize/
There are various examples. Try resizing your window and see how elements inside container elements adjusted.
Example with js fiddle
In that resize() event is bound to an elements having class "test" and also to the window object and in resize callback of window object $('.test').resize() is called.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
See this

My first thought is to use a custom event system. You can find a pure javascript one here ( http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/ )
After including his code, you can do something like this:
function myFunction(){
alert('The DIV was resized');
}
div_elm = document.getElmentById('div-to-resize');
EventTarget.call(div_elm);
div_elm.addListener("resize", myFunction);
Then later, just add one line to wherever you are resizing the div.
div_elm.width += 100 //or however you are resizing your div
div_elm.fire("resize");
I think that should work for you.
EDIT:
If you are not the one coding the resizing, then my first thought is something like this:
var resizeScannerInterval_id = (function(div) {
var width = div.offsetWidth;
var height = div.offsetHeight;
var interval_id = setInterval(function() {
if( div.offsetWidth != width || div.offsetHeight != height )
width = div.offsetWidth;
height = div.offsetHeight;
div.fire();
}
},250);
})(document.getElementById('div-id'))

There is a very efficient method to determine if a element's size has been changed.
http://marcj.github.io/css-element-queries/
This library has a class ResizeSensor which can be used for resize detection. It uses a event-based approach, so it's damn fast and doesn't waste CPU time.
Please do not use the jQuery onresize plugin as it uses setTimeout() loop to check for changes. THIS IS INCREDIBLY SLOW AND NOT ACCURATE.

Related

how to avoid windows resize triggering multiple times which is triggered by other events

I Found resize code in my page is triggeing more than once during orientation change in devices. Suspecting this is due to other events like page scroll happening during page mode change from Landscape to Portrait and vice versa. I need to write logic in window resize but its calling more than once. Is there any way we can avoid other events impacting window resize
Window resize event fires multiple times during each window resize. As Rory McCrossan points out above, the event fires once for each pixel it changes.
An option is to use a debounce function, such as that described by David Walsh:
https://davidwalsh.name/javascript-debounce-function
Here is another useful article, describing the difference between throttling and debouncing:
https://css-tricks.com/the-difference-between-throttling-and-debouncing/
Finally, you can use the less elegant (but equally effective) method of using a global variable to keep track of when you wish to allow the resize event to fire.
var ok_to_resize=true;
$(function(){
$(window).resize(function(){
if (ok_to_resize){
//run your resize code
ok_to_resize = false;
setTimeout(function(){
ok_to_resize = true;
},500);
}
}); //END window.resize
}); //END document.ready

javascript: detect when the appearance of the document has changed

Is there a way to detect when the appearance of the document has changed? For example:
$(document).on('change??', function () {
console.log('My aspect has changed');
});
// changes the appearance of a particular div
$('#my-div').css({width: 320, height: 240});
Also, is there a kind of 'render' event? This event would be fired every time the browser redraws the page. For example:
$(document).on('render', function () {
console.log('The page has been redrawn');
});
Don't know of any event like that, but if you are in control of all the changes you can easily cause your own events.
Here is a simple JQuery based example to illustrate the idea.
$( "#test" ).on( "mysitechanged", function( event, param1, param2 ) {
alert( 'changed' );
});
$( "#test").trigger( "mysitechanged", [ "Custom", "Event" ] );
http://api.jquery.com/trigger/
Here is info on how to do it in pure JavaScript
How to trigger event in JavaScript?
Since i think you're trying to detect whether the aspect has changed or not, this is what you're looking for.
window.onresize = function(){
// your code goes here;
}
Here is a good example of how the window.resize event is handled: http://jsfiddle.net/CoryDanielson/LAF4G/
I am on the lookout for that too. Apparently not. However it should be possible to implement one.
As far as I know, for the document to change appearance, one of the following is true:
The DOM has changed
The viewport changed (resize, orientation change, media changed, etc.)
You can detect changes to the DOM using MutationObserver, and detect viewport changes using native JavaScript events (onresize, etc.).
I am not sure whether this is necessary or useful (events should cover all realistic cases), but window.matchMedia(media).addListener() will also notify you about media changes to the viewport.
A DOM or viewport change does not necessarily imply a change of appearance, so then you should do some measurements on the page to verify whether anything changed.
More realistically and pragmatically, assuming that you build the page or app, you should be able to predict what would cause a change of appearance (ex: new content loaded through ajax, the user typed something in or clicked a button, new message received, page resized, etc.) and watch for these actions instead.

Responsive Design Using JavaScript

I am trying to make a grid add columns when enough room is available for another one. I have the code properly written to do this; but my issue is, how do I make a JavaScript event to constantly check to see if there if enough room to add a column. This is easy in CSS using media queries, but I inherited this code, and it cannot be done in CSS. So, I need a function for while a user is dragging the browser window border (to make the width larger), and inside of this function, do the responsive checking to see if a column can be added. Does this make sense? If you need more information, please let me know. Thanks very much in advance.
Bind an event listener to the window resize
window.onresize = function() {
//do your thing
}
OR the newer (won't work in IE8 or lower, use attachEvent instead)
window.addEventListener("resize", function() {
//do your thing
})

Is it safe to call jQuery's resize() function to execute my own resize handler?

I am defining a resize handler that positions some elements on the screen, like this:
$(window).resize(function() {
// Position elements
}
I also want to execute this functionality when the page first loads, so I just add the following right after the above code:
$(window).resize();
This works just fine. However, I'm wondering if I may trigger any side effects, harmful or not, by calling this function - I really just want to execute my own resize handler. Of course, I could do the following to make sure that I execute only my handler:
var positionElements = function() {
// Position elements
}
$(window).resize(positionElements);
positionElements();
However, I'm new to JavaScript and I want to keep my code as concise as possible - this adds some boiler plate code to the mix.
Edit: In fact, my code can be shortened even more by using chaining. Like this:
$(window).resize(function() {
// Position elements
}).resize();
I cant see how it should be harmful, anything that could be triggered by a resize that is actually destructive should be avoided in the first place. What you are doing by using calling $(window).resize() is the same as the user resizing the window.
TL;DR; Yes its safe.

jQuery event to detect when element position changes

I would like to know if there is a jQuery event that I can use to determine when a particular DIV's top property has changed.
For instance, I have invisible content above a DIV. When that content becomes visible, the DIV is shifted down. I would like to capture that event and then use the offset() function to get the X/Y coordinates.
The easy answer is that there are no events in the DOM for detecting layout updates.
You have a couple options the way I see it:
Poll, nasty but it may work depending on your update frequency requirements.
Tap into whatever event causes the invisible DIV to change size and do whatever you need to do in that handler
I shall correct myself.
I took a look at the DOM and noticed the DOMAttrModified event and found this JQuery Plug-In that you might be able to leverage to do what you want.
As the article mentions, it works great in IE and Firefox but seems to have problems in WebKit.
I thiiink you should be able to do:
$(document).ready( function (){
$("#mydiv").bind("movestart", function (){ ...remember start position... });
$("#mydiv").bind("moveend", function (){ ...calculate offsets etc... });
});
$("#someId").resize(function () {
// your code
});

Categories

Resources