I want to call my code when the width of the block I listen to changes. How to?
onresize
is invoked only when the size of the window changes.
There's no default event provided by browser when the width of your element is changing. However, just like @Leo mentioned, you can register and trigger your own event.
There are 3 steps you have to:
The sample code is here:
$(function() {
var $square = $('.square');
// Register a custom event and bind an event handler on it
$square.on('square.resize', function() {
console.log('Square is resized!');
});
// Trigger that event when you change the square size
function resizeSquare() {
$square.width($square.width() + 10);
$square.height($square.height() + 10);
$square.trigger('square.resize');
}
// Anytime you resize the square, it will trigger 'square.resize' event
// In this example, I am using setInverval() to resize the square, but you could
// change it into any ways you like
setInterval(resizeSquare, 1000);
});
You may check here for CodePen Live Demo