Mysterious javascript bug that is depending on what plot object names are used in R shiny app

给你一囗甜甜゛ 提交于 2019-12-02 03:56:10

I don't understand why the behavior depends on the ids but here is a workaround:

jscolor <- c(
  "function toggleColor(id){",
  "  var color = document.getElementById(id).value;", # get the color of the colourpicker
  "  var ids = id.split('_');", # split the id
  "  var plotAid = ids[2];", #get the id of plotA (plotw or 3)
  "  var plotBid = ids[3];", #get the id of plotB (plot2 or 4)
  "  var index = parseInt(ids[4]) - 1;", #get the trace number to target
  "  var plotA = document.getElementById(plotAid);", #get the plot element
  "  if(plotA.innerHTML !== ''){",
  "    var dataA = plotA.data;", #access the plot data
  "    var markerA = dataA[index].marker;", #access the plot's markers
  "    markerA.color = color;",  # set the marker color
  "    Plotly.restyle(plotA, {marker: markerA}, [index]);", #restyle plotA
  "  }",
  "  var plotB = document.getElementById(plotBid);", # repeat steps for plot2
  "  if(plotB.innerHTML !== ''){",
  "    var dataB = plotB.data;",
  "    var markerB = dataB[index].marker;",
  "    markerB.color = color;",
  "    Plotly.restyle(plotB, {marker: markerB}, [index]);",
  "  }",
  "};"
)

EDIT

There's a problem on startup with this workaround, as noted by the OP. Here is another workaround. It just adds a delay of 1ms.

jscolor <- c(
  "function toggleColor0(id){",
  "  var color = document.getElementById(id).value;", # get the color of the colourpicker
  "  var ids = id.split('_');", # split the id
  "  var plotAid = ids[2];", #get the id of plotA (plotw or 3)
  "  var plotBid = ids[3];", #get the id of plotB (plot2 or 4)
  "  var index = parseInt(ids[4]) - 1;", #get the trace number to target
  "  var plotA = document.getElementById(plotAid);", #get the plot element
  "  var dataA = plotA.data;", #access the plot data
  "  var markerA = dataA[index].marker;", #access the plot's markers
  "  markerA.color = color;",  # set the marker color
  "  Plotly.restyle(plotA, {marker: markerA}, [index]);", #restyle plotA
  "  var plotB = document.getElementById(plotBid);", # repeat steps for plot2
  "  var dataB = plotB.data;",
  "  var markerB = dataB[index].marker;",
  "  markerB.color = color;",
  "  Plotly.restyle(plotB, {marker: markerB}, [index]);",
  "};",
  "function toggleColor(id){",
  "  setTimeout(function(){toggleColor0(id);}, 1);",
  "}"
)

In fact this also works with a delay of 0ms:

setTimeout(function(){toggleColor0(id);}, 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!