Category / Section
How to invoke the JavaScript function after clicking the hyperlink applied cells in a JavaScript Spreadsheet
2 mins read
This knowledge base article explains you how to invoke the JavaScript function after clicking the hyperlink applied cells in a JavaScript Spreadsheet.
We’ve bound the click event for the hyperlink (“e-hyperlink” class) to cells in the created and beforeCellRender events. And then call the custom JavaScript function by preventing the spreadsheet’s default hyperlink action.
[HTML]
<div id="spreadsheet"></div>
[TS]
import { enableRipple } from '@syncfusion/ej2-base';
enableRipple(true);
import { Spreadsheet } from '@syncfusion/ej2-spreadsheet';
import * as dataSource from './default-data.json';
//Initialize Spreadsheet component
let spreadsheet: Spreadsheet = new Spreadsheet({
sheets: [
{
name: 'Car Sales Report',
ranges: [{ dataSource: (dataSource as any).defaultData }],
columns: [{ width: 150 }, { width: 130 }, { width: 100 }],
},
],
created: (): void => {
//Applies cell and number formatting to specified range of the active sheet
spreadsheet.cellFormat(
{ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' },
'A1:F1'
);
// Add hyperlink to the range of cells.
spreadsheet.addHyperlink('https://www.google.com/', 'B2:B5');
// Custom function to bind the click event.
bindClickEvent();
},
beforeCellRender(args: CellRenderEventArgs): void {
if (args.cell && args.cell.hyperlink) {
// Custom function to bind the click event.
bindClickEvent(args.element);
}
},
});
spreadsheet.appendTo('#spreadsheet');
function bindClickEvent(cellRenderElement?: HTMLElement): void {
//Bind the JavaScript function for the hyperlink element.
let elements: HTMLCollection = cellRenderElement
? cellRenderElement.getElementsByClassName('e-hyperlink')
: document.getElementsByClassName('e-hyperlink');
for (let i: number = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function (event) {
// Prevent the default action performed.
event.preventDefault();
// Call your own custom function.
handleElementClick(event.target as Element);
});
}
}
// Your custom JavaScript function
function handleElementClick(clickedElement: Element): void {
alert('You have choosen the ' + clickedElement.textContent + ' car model.');
// Add your desired functions here.
}
Sample link:
https://stackblitz.com/edit/uzvann-dbvxyo?file=index.ts,index.html
Output:
For further information about this, see the documentation that follows.