How to Trigger the Window Resize Event in JavaScript

How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
//do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});

var elem = document.getElementById(id);

return elem.dispatchEvent(event);
}

How to trigger window resize event using vanilla javascript?

You are most likely getting downvoted as people will see it as a duplicate, however from the you might not need jquery website:

IE9+

Trigger native

// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var el = document; // This can be your element on which to trigger the event
var event = document.createEvent('HTMLEvents');
event.initEvent('resize', true, false);
el.dispatchEvent(event);

Trigger custom

var el = document; // This can be your element on which to trigger the event
if (window.CustomEvent) {
var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('my-event', true, true, {some: 'data'});
}

el.dispatchEvent(event);

Fake a window resize, to make all resize-only JavaScript load

Just call $(window).trigger('resize'); it will trigger a resize and whatever you register on the resize will be called.

$(window).resize(function() {  alert("Work done when resize is being called");});
$(window).resize(function() { alert("More work");});
$("*").click(function(){ alert("Triggering resize"); $(window).trigger('resize');});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Click anywhere to trigger the resize

How to trigger window resize event in Angular

You can trigger window.resize event by

window.dispatchEvent(new Event('resize'));

And for listening to window.resize, use HostListener as below example:

@HostListener('window:resize', ['$event'])
sizeChange(event) {
console.log('size changed.', event);
}

live demo

How to trigger a window on resize event from another window?

Having spent some time on this, I decided to update my answer as I found a more efficient solution than using localStorage which is what one of the other forum members suggested to look at, and was in fact the core of my original answer before updating it.

So, have a look at Broadcast Channel API

A rather cool way in creating a publish/subscribe communication channel between browser TABs & Browser Windows, which I believe is only intended to operate within the same origin/domain (but that works for me :)

OK, so in my example below, I essentially have a Web browser Window A & Window B.

Window A is my native app, I have a need to open up a new window (Window B). In my case I'm opening up this new window to display a chart. When the window B is resized by the end user, I want to trigger a JavaScript function that is stored in Window A in order that I can re-draw the chart to fit the new canvas size.

The cool thing with the Broadcast Channel API is that you can pass objects/arrays and other goodies through the channel, most of the examples found on the web are very basic and show only passing a simple string message so I thought it'd be better to show a sample using an object.

In the example below, you'll see that I instantiate the broadcast channel (bs) in the script we add to Window B only, because this same script is already present in Window A, in essence you only need to new up an instance of the bc channel once, the browser debug will warn you anyway if you try and new up the same channel more than once.

Sample code in Window A:

// window.open(URL, name, specs, replace)
// _blank - URL is loaded into a new window, or tab. This is default
// _parent - URL is loaded into the parent frame
// _self - URL replaces the current page
// _top - URL replaces any framesets that may be loaded
// name - The name of the window(Note: the name does not specify the title of the new window)
function openWindow(chartId, chartType) {

var windowName = 'Chart' + chartId;
var w = window.open('_blank', windowName, 'left=0,top=0,toolbar=0,scrollbars=2,status=0');

// We html we want to add to the new Window B
var myHtmlCode =
'<html>'
+ '<head>'
//+ "<script type='text/javascript'>"
//+ "/* this is inline script inserted by JavaScript, below is a function converted to it's string representation */"
//+ someFuncInVariable.toString(); // Sample js function.
//+ "</script>"
+ '<style>'
+ '.chartContainer { position: relative; height:100%; min-height:100%; width:100%; min-width: 100%; outline: none; touch-action: none; background-color: #191919; padding: 0px; }'
+ '</style>'
+ '</head>'
+ '<body>'
// This is the js script that we open up in the new Window B
+ "<script type='text/javascript' src='/js/chart-custom-scripts/chartWindow.js'></script>"
+ '<div class="chartContainer container-fluid p-0 m-0" id="canvasContainer">'
+ '<canvas class="" tabindex="1" id="chartCanvas" aria-label="Chart Canvas" role="img"></canvas>'
+ '<div value="' + chartId + '" id="chartIdDiv"></div>'
+ '<div value="' + chartType + '" id="chartTypeDiv"></div>'
+ '</div>'
+ '</body>'
+ '</html>';

w.document.write(myHtmlCode);
w.document.close();
}

// Note: the bc was instantiated in the chartWindow.js file which is
// also added as a script to a new window when opening up a new chart.
// see https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
bc.onmessage = (messageEvent) => {
const data = messageEvent.data

switch (data.type) {

case 'chartResized':
var chartId = data.object.chartId;
var chartType = data.object.chartType;
//console.log(data.object.chartId); // testing only...
//console.log(data.object.chartType); // testing only...

switch (chartType) {

case "bar":
// code block
renderBarChartConfig(chartId, 'resize'); // Run the function below to re-draw the chart.
break;

case "horizontalBar":
// code block
renderBarChartConfig(chartId, 'resize'); // Run the function below to re-draw the chart.
break;

case "line":
// code block
renderBarChartConfig(chartId); // Run the function below to re-draw the chart.
break;

case "pie":
// code block
renderBarChartConfig(chartId); // Run the function below to re-draw the chart.
break;

case "doughnut":
// code block
renderBarChartConfig(chartId); // Run the function below to re-draw the chart.
break;

case "polarArea":
// code block
renderBarChartConfig(chartId); // Run the function below to re-draw the chart.
break;

case "radar":
// code block
renderBarChartConfig(chartId); // Run the function below to re-draw the chart.
break;
}
break
default:
console.log('we received a message')
}
};

Sample Code script added to Window B:

// Create or join the broadcast channel.
const bc = new BroadcastChannel('charts_channel');

// Run the function when the page loads.
window.onload = function () {

setTimeout(function () {
// Eventlistener for when the window is resized.
// We add a small time delay in order that we only
// fire the reisze event once the window has resized as opposed
// to firing multiple events throughout the course of the window
// being resized.
// see https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/
var resizeId;
window.addEventListener('resize', function () {
clearTimeout(resizeId);
resizeId = setTimeout(doneResizing, 500); // 500 milliseconds pause before we process reseize event.
});

}, 2000);
}

function doneResizing() {
//whatever we want to do
// Run code here, resizing has "stopped"
var chartId = this.document.getElementById("chartIdDiv").getAttribute('value');
var chartType = this.document.getElementById("chartTypeDiv").getAttribute('value');

var chart = {
chartId: chartId,
chartType: chartType
};

bc.postMessage({ type: 'chartResized', object: chart });
}


Related Topics



Leave a reply



Submit