In this post, we will add our first event to the EWA and see how we can get an even more integrated experience. The feature we are going to code in this step is to give users the ability to click in our dashboard on a specific person alias in one of the sheets and use that value to show a picture of that person on the side of the web-part page.
Step 1 – Listening to an event
But before we can do all this image handling, first thing’s first – we need to listen to events. Hooking up event is typically done in the ewaApplicationReady() method described before – that’s where the EWA is ready and able:
The rangeArgs parameter in the function will contain information on the range clicked. Specifically, it will contain the following three methods:
getRange() – This returns the Range object that’s behind the cell that was selected.
getWorkbook() – The workbook object that is currently loaded in the EWA.
getFormattedValues() – The value that’s in the cell.
In our case, we will use the getFormattedValues() to figure out what the text is in the cell and use that to display the image.
Step 2 – Adding the image tag so that we can display an image
In the first post, the HTML fragment we are using inside the content-part contains a single <script> tag containing our code. It is obviously quite possible to also have any other HTML in there – in this case, we will add an IMG tag:
Step 3 – Setting the image due to cell change
We will modify the cellchanged() function in the following manner:
What this does is take the formatted value of the cell that was selected and uses it in a URL that is set into the img tag – in this case, the URL will be /personalpages/shaharp.jpg when my alias is picked. And here’s how this looks in the browser:
That’s great! But watch what happens when a different random cell is selected (say, the one that says “Alias”):
The problem is that we are indiscriminately setting the image. Instead, we need to make sure that the range where the user clicked makes sense.
Step 4 – Looking at the Range object
To do this, we will take the Range object that comes back as part of the rangeArgs parameter and use it to check the coordinates of the cell that was selected. If it falls under our scenario (the column in question), only then will we actually set the image:
The code uses the getSheet().getName(), getColumn() and getRow() calls on the range to figure out exactly where the selection is, and if it falls under the range we are interested in, only then will we go and set the URL for the image.
And that’s it for this post – we saw how to hook up events and then we saw how to use the argument in the event to figure out where the user clicked in the document and what the content of the selection is. Next up, we will see how we can write back values into the workbook.