I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called.
I found window.resizeTo()
can trigger the function, but is there any other solution?
This question is related to
javascript
jquery
events
Response with RxJS
Say Like something in Angular
size$: Observable<number> = fromEvent(window, 'resize').pipe(
debounceTime(250),
throttleTime(300),
mergeMap(() => of(document.body.clientHeight)),
distinctUntilChanged(),
startWith(document.body.clientHeight),
);
If manual subscription desired (Or Not Angular)
this.size$.subscribe((g) => {
console.log('clientHeight', g);
})
Since my intial startWith Value might be incorrect (dispatch for correction)
window.dispatchEvent(new Event('resize'));
In say Angular (I could..)
<div class="iframe-container" [style.height.px]="size$ | async" >..
A pure JS that also works on IE (from @Manfred comment)
var evt = window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
Or for angular:
$timeout(function() {
var evt = $window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, $window, 0);
$window.dispatchEvent(evt);
});
With jQuery, you can try to call trigger:
$(window).trigger('resize');
Combining pomber's and avetisk's answers to cover all browsers and not causing warnings:
if (typeof(Event) === 'function') {
// modern browsers
window.dispatchEvent(new Event('resize'));
} else {
// for IE and other old browsers
// causes deprecation warning on modern browsers
var evt = window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
}
I believe this should work for all browsers:
var event;
if (typeof (Event) === 'function') {
event = new Event('resize');
} else { /*IE*/
event = document.createEvent('Event');
event.initEvent('resize', true, true);
}
window.dispatchEvent(event);
window.dispatchEvent(new Event('resize'));
window.resizeBy()
will trigger window's onresize event. This works in both Javascript or VBScript.
window.resizeBy(xDelta, yDelta)
called like window.resizeBy(-200, -200)
to shrink page 200px by 200px.
I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:
$(window).bind('resize', function () {
resizeElements();
}).trigger('resize');
just
$(window).resize();
is what I use... unless I misunderstand what you're asking for.
You can do this with this library. https://github.com/itmor/events-js
const events = new Events();
events.add({
blockIsHidden: () => {
if ($('div').css('display') === 'none') return true;
}
});
function printText () {
console.log('The block has become hidden!');
}
events.on('blockIsHidden', printText);
Source: Stackoverflow.com