Guide to updating the htmlOutput in shiny with JavaScript

An interactive application showcases a sentence on the screen.

Users have the ability to select specific parts of the sentence and apply custom markup by clicking the Mark button. The sentence should then reflect this action in real-time.

For example:
Input: A sample sentence for demonstration
Selection: sentence for
Desired output: A sample

<markup> sentence for </markup>
demonstration

Below is the code for the shiny app along with the relevant JavaScript function:

library(shiny)
ui <- fluidPage(
  tags$head(tags$script(src="addMarkup.js")),
  titlePanel("Mark text selection"),
    mainPanel(htmlOutput("content"),
      actionButton("Mark", "Mark", onclick="addMarkup()")
    )
  )

server <- function(input, output) {
  sentence <- "A sample sentence for demo" 
  output$content <- renderText(sentence)
}

shinyApp(ui = ui, server = server)

addMarkup.js

function addMarkup(){
  var sent="";
  sent= document.getElementById("content").innerHTML;
  var selection="";
  if(window.getSelection){
    selection = window.getSelection().toString();
  }
  else if(document.selection && document.selection.type != "Control"){
    selection = document.selection.createRange().text;
  }
  marked = "<markup>".concat(selection).concat("</markup>");
  result = sent.replace(selection, marked);
  alert(result);
  document.getElementById("content").innerHTML = result;
}

Issue: Although the alert(result) displays the desired output, the subsequent line fails to update the content.

Are there alternative ways to achieve this functionality without relying on JavaScript? Please share your insights.

Answer №1

Your solution is effective. The issue lies in the fact that the <markup> tag is not valid in HTML. By simply changing <markup> to <mark>, your code will function correctly.

marked = "<mark>".concat(selection).concat("</mark>");

https://i.sstatic.net/TQ8yS.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Having trouble calling the edit function in React? Keep getting the error message "this.props.onContactSubmit is not a function"? Let's

I am currently experiencing an issue with React. I am trying to edit a contact from the contactList but keep encountering an error: Uncaught TypeError: this.props.handleContactEditSubmit is not a function... var ContactBox = React.createClass({ getInitia ...

An error occurred with nextJS and the current date. The text content does not align with the server-rendered HTML, raising a warning that the content does not

When working on a component with React, NextJS and M-UI, I encountered an issue while trying to retrieve a date. The error message I received was: Unhandled Runtime Error Error: Text content does not match server-rendered HTML. Warning: Text content did n ...

Creating 3D text using textGeometry in React Three Fiber results in a cube-shaped representation

Trying to create 3D text in React Three Fiber by following this tutorial but ending up with a cube instead of text. This is the code snippet I used: import { extend } from "@react-three/fiber" import { FontLoader } from "three/examples/jsm/l ...

Divide information in the chart

<table id="tab"> <tr><td class="sub">mmmmm</td><td class="sub">jjjjj</td></tr> <tr><td class="sub">lllll</td><td class="sub">wwwww&l ...

Chrome not responding to ajax requests

Having an issue with a script that uses ajax to post text: <?php if (isset($_POST['q'])) { echo 'q is '.$_POST['q']; } else { ?> <!DOCTYPE HTML> <html> <head> <script ...

Is it possible to retrieve the current CSS value set by a media query using JavaScript?

Currently working on a website project that involves accessing and manipulating the display property of a menu. The goal is to toggle the menu open or closed based on its current state. In my setup, the initial state of the menu is defined as closed using ...

A commitment was formulated within a handler but failed to be returned from it

After a user clicks on the button (#lfdsubmit), it triggers the function (LFD_SearchContainer()) which is expected to return a promise. However, errors are occurring at LFD_SearchContainer('EISU1870725') .then(container => { ST2.db2(contai ...

Passing state data from parent to child components in React

I am currently facing an issue with binding the state of a parent component to a child component. Here is a snippet of the code: Parent Component: class ParentForm extends React.Component { constructor(){ super(); this ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

Challenges in Implementing Jquery Autocomplete with Spring Framework Version 2.5.6

I am facing an issue with displaying an autocomplete list using JQuery and Spring 2.5.6. I am able to retrieve the JSON data on the front end, but I am unable to display it properly. $(function() { $("#globalSearch").autocomplete({ source: fun ...

Angular.js can dynamically add a class to an element based on the current page being viewed

Currently, my goal is to assign the class post to my div with id #wrap when I am on the page /post. Here's what I have so far: $routeProvider when('/post', { templateUrl : 'views/post.php', controller : 'postCtrl&ap ...

What are some strategies for optimizing Next.js applications for mobile devices?

https://i.stack.imgur.com/mWmWG.png After realizing that the structure of my Next.js app doesn't align with Create React App's folder system, I'm stuck on how to effectively scale my website for mobile devices. In my confusion, I'm una ...

Clicking the button in jQuery results in no action

Currently, I am delving into the world of jQuery and have encountered a roadblock with a particular issue. Below is the code snippet in question: $(function(){ var gotProducts=new Array(); var productsWithDelete=new Array(); $('.addProducts ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Adding .js extension to relative imports in TypeScript compilation for ES6 modules

This particular issue may appear simple at first glance, but determining the required settings/configurations to resolve it is not straightforward. Below are the directory structure and source code for a Hello World program: Directory Structure: | -- Hel ...

Reducing the amount of code needed for mental challenges

This is a mental exercise involving a coding challenge in the realm of R programming. Imagine a scenario where there are 15 candles placed on a table. Through three rounds, you will need to either light a candle if it is currently unlit, or extinguish it ...

Facing CORS issue when trying to use the app on a device without network activity, although it works fine on

Currently, I am in the process of developing an Ionic app. Interestingly, the app runs smoothly in the browser; however, when it comes to running it on the device, the HTTP requests fail to load. Upon inspecting the app using Safari remote debugging, no er ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

Request a HTML variable and send it to JavaScript

My latest project involves a Binary to Decimal Calculator that is now fully functional, but I am looking to integrate an HTML input into it. <html> <input placeholder="00000000" name="htmlinput"></input> <input id="clickMe" type="butt ...