I am dealing with a datatable with clickable element. A column of the row contains a hyperlink. When the hyperlin is clicked I don't want the row click event to be fired or managed (to select / deselect).
What I have tried on R Shiny:
function preventDefault(e) {
e.preventDefault();
e.stopPropagation();
return false;
}
The element in DataTable which contains link:
<a href="#" onclick="preventDefault(event)";>
But nothing happened.
The full source code:
library(shiny)
library(DT)
library(dplyr)
ui <- fluidPage(
# Application title
DT::dataTableOutput("DTExample")
)
server <- function(input, output) {
dat <- head(iris)
dat <- dat %>% mutate(clickme = '<a href="#"
onclick="event.preventDefault(); event.stopPropagation(); alert(event); return false;";
>CLICKME</a>')
output$DTExample<- renderDataTable({
datatable(dat, escape = FALSE, class = 'cell-border stripe')
})
}
# Run the application
shinyApp(ui = ui, server = server)
You can disable row selection by datatable(..., selection = 'none') , or use the single selection mode by selection = 'single' . The default selection mode is multiple selections (try the table below).
Just return false in the selection event. It will stop selection of that particular row.
The problem happened because the "highlight action" is bind to "mousedown", which is happen earlier than the "click" event. You can not prevent the event happened before, right?
One simple solution is to use onmousedown
instead of onclick
dat <- dat %>% mutate(clickme = '<a href="#"
onmousedown="event.preventDefault(); event.stopPropagation(); alert(event); return false;";
>CLICKME</a>')
BTW, you can use chrome F12 to check the event listener. You can remove some listener to see the difference and find which listener is for "highlight"
Also, I found this because when I click the link but not release, the highlight happened but the click not happened. Then I realize this could be the key and check the event listener using Chrome. I hope you can understand the way of debugging!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With