Detect browser window size

I want to detect the window size of the browser then store it in a global variable to use it elsewhere. Here’s my script so far, but it is returning the values inside span:

import dash
from dash import html, dcc, Input, Output, clientside_callback, callback

app = dash.Dash(__name__)

app.layout = html.Div([
    html.P(id='window-size-display', children=[
        "Current Window Size: Width: ",
        html.Span(id='width'),
    ]),
])


clientside_callback(
    """function () {
    dash_function()
    return window.dash_clientside.no_update
}""",
    Output("window-size-display", 'children'),
    Input("window-size-display", 'children')
)




if __name__ == '__main__':
    app.run_server(debug=True)

and this is the javascript code:

function dash_funtion(){
    function updateWindowSize() {
        // Get the innerWidth and innerHeight of the browser window
        var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

        // Update the HTML elements with the window size information
        document.getElementById('width').textContent = width;
    }

    // Initial update of the window size display
    updateWindowSize();

    // Attach an event listener to update the window size display on window resize
    window.addEventListener('resize', updateWindowSize);
}

Hi @mo_taweel have a read here:

It’s recommended to use dcc.Store() to share information between callbacks. It’s pretty much what you already have.

You could use dash_breakpoints to retrieve and use window dimensions /breakpoints on the server side :slight_smile: