Daily Tips - Write the Simplest Client-side Callback 🌭

Hi there,

Last time, I wrote two callbacks in the example to disable the input box and the button.

@app.callback(
    Output(
        {
            'category': 'questionnaire',
            'type': 'choice+blank',
            'additional': True,
            'index': MATCH
        }, 'disabled'),
    Input(
        {
            'category': 'questionnaire',
            'type': 'choice+blank',
            'additional': False,
            'index': MATCH
        }, 'value'))
def disable_input(v):
    return False if v == 'Yes' else True


@app.callback(
    Output(
        btn, 'disabled'),
    Input(
        {
            'category': 'questionnaire',
            'type': ALL,
            'additional': False,
            'index': ALL
        }, 'value'))
def disable_btn(answer):
    return False if all(answer) else True

The question is, is it necessary to bother the server for such a tiny matter? Oh, come on! Leave it to the client-side callback to handle.

window.dash_clientside = Object.assign({}, window.dash_clientside, {
    clientside: {
        disable_input: function (v) {
            if (v === 'Yes') { return false } else { return true }
        }
    }
});

Since arrow function expressions were introduced in ES6, we’re going to get this. :person_fencing:

window.dash_clientside = Object.assign({}, window.dash_clientside, {
    clientside: {
        disable_input: v => v === 'Yes' ? false : true,
        disable_btn: answers => answers.every(Boolean) ? false : true
    }
});
app.clientside_callback(
    ClientsideFunction(namespace='clientside', function_name='disable_input'),
    Output(
        {
            'category': 'questionnaire',
            'type': 'choice+blank',
            'additional': True,
            'index': MATCH
        }, 'disabled'),
    Input(
        {
            'category': 'questionnaire',
            'type': 'choice+blank',
            'additional': False,
            'index': MATCH
        }, 'value'))


app.clientside_callback(
    ClientsideFunction(namespace='clientside', function_name='disable_btn'),
    Output(
        btn, 'disabled'),
    Input(
        {
            'category': 'questionnaire',
            'type': ALL,
            'additional': False,
            'index': ALL
        }, 'value'))

Don’t forget to put this piece of JS in your assets/ folder.

Hope this helps you. XD

Keywords: Client side Callbacks, JavaScript

2 Likes

Love this :heart_eyes:

2 Likes

On the Python side, it would be written like:

app.clientside_callback(
    f"(href => window.innerWidth < 750 ? {[i for i in df.columns if i not in ['GAME','RATIO','COMP %']]} : [])",
    Output("table", "hidden_columns"),
    Input("loc", "href"),
)