How to run javascript byc clicking a cell in google sheets? - javascript

Google sheets allows you to write scripts in javascript, the same way excel lets you write VBA to automate tasks.
I'd like to make a cell in my google spreadsheet clickable, so that when it is clicked, my function will run.
I've found that it's possible to create custom buttons by inserting a drawing, but I'd really like this to be any time a particular cell is clicked, rather than a button which can move around and looks awkward in the sheet.
Is it possible?
Thanks for any advice.

There is not an onClick event for cells but what you can do is instruct the user to enter your formula/custom function into the cell as described at https://developers.google.com/apps-script/execution_custom_functions?hl=es#using.
Similarly, you could have the cell pre-populated with the formula and simply ask the user to edit it and then press enter to run the function.

What you are searching for, is onSelectionChange(), it runs automatically when a user changes the selection in a spreadsheet.
Try the following code and read the developers link.
/**
* The event handler triggered when the selection changes in the spreadsheet.
* #param {Event} e The onSelectionChange event.
*/
function onSelectionChange(e) {
// Set background to red if a single empty cell is selected.
var range = e.range;
if(range.getNumRows() === 1
&& range.getNumColumns() === 1
&& range.getCell(1, 1).getValue() === "") {
range.setBackground("red");
}
}

You can draw you own button and attach a sript to it. Edit it all transparent, and write no text.
Then place it on the cell you wish, resizing to fit inside the cell's area.
Add A Google Sheets Button To Run Scripts

Related

Tabulator - How to enable editing on all table cells at once?

I use a tabulator from https://tabulator.info/
There is an editing option in this tabulator. I know about enable and editor. But I point out that this is not what I mean.
My goal is to set the edit mode on all cells of the table BUT in the form that occurs in the cell only when you click on a specific cell. Now it works in such a way that when edit mode is enabled to edit a cell you have to click on it - only then the style changes to edit style. I would like this editing style to be shown immediately on all cells at once and not just on one when clicked. I tried calling this with the cell.edit() function which mimics this, and using dispatchEvent.
cells?.forEach((cell) => {
console.log("cell edit", cell);
let cellEl = cell.getElement();
cellEl.dispatchEvent(new Event("click"));
// // cell.edit();
});
enter code here
However, I was surprised to see that the end result is to enable this mode only for the last cell in the loop. Is there any option at all to enable such editing or any other way to get the same styles after the click and before (both in edit mode)?
The problem with using cell.edit() is also that when you click anywhere the styles disappear anyway.
I'm also trying to use a formatter to solve the problem but I don't quite know how to finish it either.
column.formatter = function (cell) {
cell.getElement().classList.add("tabulator-editing");
return cell.getValue();
};

Google document add-on - setSelection() of text by sidebar button - how to make it an active selection?

Background:
I am using the setSelection() method in an google marketplace add-on for google documents.
The text is selected as expected when clicking the relevant button on the add-on's sidebar. However, this selection is not active - i.e. the selected text is highlighted in light grey instead of light blue (see example below).
Now:
What I need:
This is because the last active portion of the browser tab is the sidebar (after clicking the button), not the actual document.
Question:
Is there a way to make the button click select the text and keep the document the active portion?
Goal:
The whole purpose of this selection is to copy the selected text by Ctrl + C on the keyboard, which is not possible when the selection is not active.
Right now the user needs to use the right-click on the mouse and select Copy from the menu...
On your client-side code use google.script.host.editor.focus() to make the selection on the editor an active selection.
function showSidebar(){
var ui = DocumentApp.getUi();
var html = '<div>Hello world!</div>'
html += '<div><button onclick="google.script.host.editor.focus()">Click me!</button></div>';
ui.showSidebar(HtmlService.createHtmlOutput(html));
}
From https://developers.google.com/apps-script/guides/html/communication#moving_browser_focus_in
Moving browser focus in Google Workspace
To switch focus in the user's browser from a dialog or sidebar back to the Google Docs, Sheets, or Forms editor, simply call the method google.script.host.editor.focus(). This method is particularly useful in combination with the Document service methods Document.setCursor(position) and Document.setSelection(range).
Solution
Since your goal is to copy the selected text I would like to propose an alternative solution:
The task now will include the copying feature directly without additional user input than the button click. And it will be developed this way:
Text Selection
Get your selected text with your Apps Script function triggered by a button click:
//... Your custom logic to get the text selection
var text-to-copy = doc.setSelection(x)
.getSelection()
.getRangeElements()
.map(re => re.getElement()
.asText()
.getText())
.join(" ");
return text-to-copy;
We cannot access the user clipboard from Apps Script but with a successHandler we can pass the text-to-copy variable to the Client-Side interface.
Handling the Server-Side return value
In the following way we can pass the text back to the HTML sidebar.
<!-- HTML Interface Index.html -->
<button onclick="google.script.run.withSuccessHandler(copyToClipboard).setSelection()">
Click Here
</button>
<script>
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
</script>
We can now leverage the native client-side functionality to copy that text directly to the user clipboard without having her/him to Ctrl+C once your script finished.
A good practice in this case would be to provide a visual feedback to your user once the copy procedure has finished.
Reference
withSuccessHandler(function)

Does anyone have or know of any example of a custom popup editor for Tabulator?

We are seeking a working example of a popup editor (ideally textarea) using Tabulator. Does anyone have or know of one of a working example?
The Tabulator folks say this is up to the dev https://github.com/olifolkerd/tabulator/issues/2048. And while we can see not providing this as part of Tabulator proper, an example showing how to glue it together would be nice because it is Tabulator the integration is with.
And yes, we are aware there are other grids that have this already, but they have not met our needs in other areas that Tabulator has, so we'd really like to tackle this with Tabulator.
Here is a rough start using a JQuery UI dialog, but we cannot figure out how to get he cell value to update and close the dialog https://jsfiddle.net/1kmrLoj8/16/
function onChange(e){
if(((cell.getValue() === null || typeof cell.getValue() === "undefined") && editor.value !== "") || editor.value !== cell.getValue()){
if(success(editor.value)){
cell.setValue(editor.value); //persist value if successfully validated incase editor is used as header filter
$(dialog).dialog('close'); //does not work
}
}else{
cancel();
$(dialog).dialog('close'); //does not work
}
}
Tabulator is only built to display tables, it does not create an elements outside of the table itself.
If you want to use modals or popups then i would suggest choosing a 3rd party modal library that works for your needs and trigger it from an event in Tabulator.
If you want it to act as an editor then i would suggest triggering the modal on the cellClick or RowClick events.
These events get pass in a Component Object representing the cell or row that has been clicked. you can then call functions on these objects to change any updated data in the table

How to attach events on control buttons of SAPUI5's Network Graphs?

I am creating a Network Graph based on this official code sample https://sapui5.hana.ondemand.com/#/entity/sap.suite.ui.commons.networkgraph.Graph/sample/sap.suite.ui.commons.sample.NetworkGraphDimensions
I would like to disable search field (make it invisible) by default and enable it only after switching to Full Screen Mode.
Disabling search field by default is easy:
var oNetworkGraph = this.getView().byId("myGraphId");
if (oNetworkGraph.isFullScreen() === false) {
oNetworkGraph._searchField.setVisible(false);
}
The problem is that our search field and other buttons (zoom in/out, toggle legend button, etc) are not defined inside XML view neither inside controllers. I guess it's a part of either sap.suite.ui.commons.networkgraph or sap.suite.ui.commons.networkgraph.layout and being inserted on init.
Because of this issue I can't add a listener on my Full Screen Toggle Button.
You could attach yourself similarly to your search field modifications.
I've checked the code and the button is available under the class variable _oFullScreenButton. That means by oNetworkGraph._oFullScreenButton.attachPress(function() {}); You could run code when button is pressed.
Note that accessing these private APIs might break in future versions.

Create a custom function for google sheets

I know it's possible to create a function in google sheets via the script editor, I used to be able to do it, now I'm struggling.
These functions should be accessible through a cell, and be able to use a cell.
How do I create a function, and how do I use it?
It's all described quite extensively in the docs:
https://developers.google.com/apps-script/guides/sheets/functions
To write a custom function:
function DOUBLE(input) {
return input * 2;
}
Create or open a spreadsheet in Google Sheets.
Select the menu item Tools > Script editor. If you are presented with a welcome screen, click Blank Project on the left to start a new project.
Delete any code in the script editor. For the DOUBLE function above, simply copy and paste the code into the script editor.
Select the menu item File > Save. Give the script project a name and click OK.
All done! Now you can use the custom function.
Using a custom function:
Click the cell where you want to use the function.
Type an equals sign (=) followed by the function name and any input value — for example, =DOUBLE(A1) — and press Enter.
The cell will momentarily display Loading..., then return the result.

Categories

Resources