How do I detect when the width of a div with id X changes? I have a function ‘wrapLines’ which needs to be called whenever this div container’s width changes. because of following reasons
- whether the window got resized
- or any other reason like a collapsible menu opening up causing x div to decrease in width
Application uses Knockout JS and OJET(Oracle JET). so there is view and viewModel defined for html and respective js.
Please help.
I tried to use window.resize like mentioned below but it doesn’t work-
$("#" + x).on('resize', function(event) {
//call wrapLines function
});
The code below works but only for case 1. I need case 2 to pass.
$(window).on('resize', function(event) {
//call wrapLines function
});
2
Answers
Use the
ResizeObserver
API.I’ve used the ResizeObserver to create a KnockoutJS binding handler to deal with change events and update an observable with the new width. Please see
jsfiddle example: https://jsfiddle.net/martlark/L03wtzqb/36/
HTML:
Binding handler:
View controller: