I would like to make a javascript function that modifies the data of a cell ONLY if a particular condition is met. This is in the context of a datatable in R Shiny. The goal is to improve on this tremendous answer by Stephane Laurent.
What I don't understand is why adding
if($cell.data.length > 10){...}
doesn't work. In the MWE I've set the condition to > 1 - and the code works on all cells. If you set it to > 2, it does not work on any cells.
library(DT)
library(shinipsum)
text_df <- data.frame(
numbers = 1:3,
letters = LETTERS[1:3],
text = c(
"Lorem",
substr(shinipsum::lorem, 1, 100),
substr(shinipsum::lorem, 1, 5000)
)
)
js <- "
function(cell) {
var $cell = $(cell);
$cell.contents().wrapAll('<div class=\\\"content\\\"></div>');
var $content = $cell.find('.content');
if($cell.data.length > 1){
$cell.append($('<button>Read more</button>'));
$btn = $cell.find('button');
$content.css({
height: '20px',
overflow: 'hidden'
});
$cell.data('isLess', true);
$btn.click(function () {
var isLess = $cell.data('isLess');
$content.css('height', isLess ? 'auto' : '100px');
$(this).text(isLess ? 'Read less' : 'Read more');
$cell.data('isLess', !isLess);
});
}
}
"
datatable(
text_df,
rownames = FALSE,
options = list(
"columnDefs" = list(
list(
"targets" = 2,
"createdCell" = JS(js)
)
)
)
)
CodePudding user response:
I edited the other post to answer but I can develop here.
The createdCell option actually is a function with five arguments:
function(cell, cellData, rowData, rowIndex, colIndex) {
......
}
To target the cells containing more than 100 characters, you can do:
function(cell, cellData, rowData, rowIndex, colIndex) {
if(cellData.length > 100) {
......
}
}
That should be identical to cell.data().length > 100
.
To skip the first row (remembering that indexing starts at 0 in JavaScript):
function(cell, cellData, rowData, rowIndex, colIndex) {
if(rowIndex > 0) {
......
}
}