I am attempting to adjust the technique outlined in this Stack Overflow answer on how to auto-resize a textarea input using JavaScript for shiny R. I prefer not to rely on additional packages like shinyJS.
Initially, I experimented with a pure JavaScript implementation by directly embedding the script into the application (approach 1). Subsequently, I explored triggering the JavaScript function from an observeEvent function within shiny (approach 2).
Regrettably, both approaches have failed to produce the desired outcome. It appears that some crucial element is missing.
Approach 1:
library(shiny)
jsCode1 <- "
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init () {
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}
init();
"
shinyApp(ui =
fluidPage(
tags$script(jsCode1),
tags$head(
tags$style("
textarea {
border: 0 none white;
overflow: hidden;
padding: 0;
outline: none;
background-color: #D0D0D0;
}
"
)
),
shiny::tagAppendAttributes(
textAreaInput(inputId = "text",
label = "Enter text here",
placeholder = "insert your text here",
width = "100%"),
style = "width: 100%;")
),
server = function(input, output, session) {
}
)
Approach 2:
library(shiny)
jsCode2 <- "
Shiny.addCustomMessageHandler('handler1', init);
function init (el) {
var text = document.getElementById(el);
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}"
shinyApp(ui =
fluidPage(
tags$script(jsCode2),
tags$head(
tags$style("
textarea {
border: 0 none white;
overflow: hidden;
padding: 0;
outline: none;
background-color: #D0D0D0;
}
"
)
),
shiny::tagAppendAttributes(
textAreaInput(inputId = "text",
label = "Enter text here",
placeholder = "insert your text here",
width = "100%"),
style = "width: 100%;")
),
server = function(input, output, session) {
observeEvent(input$text,{
session$sendCustomMessage("handler1", message = "text")
})
}
)