DEV Community 👩‍💻👨‍💻

Bruce Axtens
Bruce Axtens

Posted on

Disabling and re-enabling a button in Google Apps Script

The requirement is to be able to click on a button, have it launch a function and then be otherwise unclickable until that function has concluded. This is my first attempt.

So have a sheet called "tester". On it is a big green button Drawing with the word "Button" on the front. This is assigned to the _Button function.

Button

Button 1a

We have a function called SwapDrawingOnActions which is defined as follows (in TypeScript):

function SwapDrawingOnActions(sheet:GoogleAppsScript.Spreadsheet.Sheet|string, actionToFind:string, actionToReplaceWith:string) : boolean {
    let replaced = false;

    if ("string" === typeof sheet) {
        sheet = SpreadsheetApp.getActive().getSheetByName(sheet);
    }

    const drawings = sheet.getDrawings();
    for (var i = 0; i < drawings.length; i++) {
        const drawing = drawings[i];
        if (drawing.getOnAction() === actionToFind) {
            drawing.setOnAction(actionToReplaceWith);
            replaced = true;
            break;
        }
    }
    return replaced;
}
Enter fullscreen mode Exit fullscreen mode

We have two demonstration functions, _Button() and _PleaseWait()

function _Button() {
    Browser.msgBox("Okay, we're about to do something important right now.");
    SwapDrawingOnActions("tester","_Button", "_PleaseWait");    
}

function _PleaseWait() {
    Browser.msgBox("Sorry, we're doing something important right now.");
    SwapDrawingOnActions("tester", "_PleaseWait", "_Button");
}
Enter fullscreen mode Exit fullscreen mode

So on the first invocation, a msgBox appears and the OnAction of the button is set to _PleaseWait. On the second invocation, the OnAction is changed back to _Button.

Button 1

Button 2

The OnAction does actually get changed, viz

Button 2a

I expect that there are other ways of doing this. Tanaike does one and it's amazing.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.