JS Copy button for Rails Action Text body element

  actiontext, javascript, ruby-on-rails

I have a little app with a section model. the section has a title and a body. The body makes use of action text.

I have created a simple copy button for the title.

<div class='mt-5 mb-5'>
    <h3 value="<%= section.title %>" id="st<%= section.id %>"><%= section.title %></h3>
    <div value="" id="<%= section.id %>"><%= section.body %></div>
    <button class="btn btn-primary mt-5" onclick="copy_function('<%= section.title %>')">Copy Title</button>
</div>
<script>
function copy_function(id) {
  var input_temp = document.createElement("input");
  input_temp.value = id;
  document.body.appendChild(input_temp);
  input_temp.select();
  document.execCommand("copy");
  document.body.removeChild(input_temp);
}
</script>

I want to make a similar button for the body, but the HTML elements make it a bit tricky.

<div class='mt-5 mb-5'>
    <h3 value="<%= section.title %>" id="st<%= section.id %>"><%= section.title %></h3>
    <div value="<%= section.body.html_safe? %>" id="sb<%= section.id %>"><%= section.body %></div>
    <button class="btn btn-primary mt-5" onclick="copy_function('<%= section.title %>')">Copy Title</button>
    <button class="btn btn-primary mt-5" onclick="copy_body_function('<%= section.body.html_safe? %>')">Copy Body</button>
</div>
<script>
function copy_function(id) {
  var input_temp = document.createElement("input");
  input_temp.value = id;
  document.body.appendChild(input_temp);
  input_temp.select();
  document.execCommand("copy");
  document.body.removeChild(input_temp);
}

function copy_body_function(id) {
  var input_temp = document.createElement("input");
  input_temp.value = id;
  document.body.appendChild(input_temp);
  input_temp.select();
  document.execCommand("copy");
  document.body.removeChild(input_temp);
}
</script>

any tips for how to handle to body HTML elements in a js button

Source: Ask Javascript Questions

LEAVE A COMMENT