3

I have the HTML code below. This is a word with a Wikipedia definition below it. The definition should be highlighted on click.

I need help in rewriting this code. So only the word will appear and the definitions should be hidden But when someone clicks on the word, the definition will be automatically copied to the clipboard. I tried searching for tips to no avail.

<p><strong>Gold</strong><br />
    <textarea cols="70" onclick="this.focus();this.select()" readonly="readonly" rows="5"
     style="color: black; background-color: lightgreen;
     border:1px solid #AD8C08">
        Gold is a chemical element with symbol Au and atomic number 79.
        In its purest form, it is a bright, slightly reddish yellow,
        dense, soft, malleable and ductile metal. Chemically, gold is
        a transition metal and a group 11 element.
    </textarea>
</p>
Michael Laszlo
  • 11,163
  • 2
  • 26
  • 45
JAMES
  • 115
  • 8

2 Answers2

1

How do I copy to the clipboard in JavaScript?

  document.execCommand('copy');

Not all browsers support it (chrome 43+ if that gives you an idea of how new it is.)

Browsers make it tough to actually copy things to the clipboard automatically. Check out this answer for more info.

However

If you wanted to just make it selected so that the user can manually copy it, make the text stored in a textarea / text field and set onclick = document.getElementById("idOfTextYouWantSelected").select(); to the "button"

For Example :

 <p>
      <strong onclick = 'document.getElementById("textAreaForGold").select();'>Gold</strong>
      <br />
      <textarea cols="70" id = 'textAreaForGold' readonly="readonly" rows="5" style="color: black; background-color: lightgreen; border:1px solid #AD8C08">
         Gold is a chemical element with symbol Au and atomic number 79.
         In its purest form, it is a bright, slightly reddish yellow,
         dense, soft, malleable and ductile metal. Chemically, gold is
         a transition metal and a group 11 element.
      </textarea>
 </p>
Community
  • 1
  • 1
Ulad Kasach
  • 7,372
  • 7
  • 41
  • 67
  • I just realize it's not a good idea to make autocopy. How about just making the definition hidden but when someone clicks on the word "Gold" the definition will be highlighted in the background so I can copy manually with Crtl+C. Any tips on that? Thanks! – JAMES Sep 22 '15 at 22:18
  • Put the text in a textarea / input field and add `onclick = document.getElementById("idOfTextYouWantSelected").select();` as a property of that button. – Ulad Kasach Sep 22 '15 at 22:22
  • Thanks everyone for sharing your knowledge! I just made a couple of changes and voila! It now works like a charm! Thanks! – JAMES Sep 22 '15 at 22:47
  • You got it bud. For the record - most of the answer i got through google from the site itself. Next time, try breaking down the problem and figuring out the pieces yourself. Youll learn more in the process. – Ulad Kasach Sep 22 '15 at 22:49
1

You can copy the content of an editable element with execCommand('copy').

If the element is non-editable, like a div, you can use the following function to select its contents:

function selectText(element) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNodeContents(element);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
  }
}

Now let's consider the problem of showing the definition when the user clicks on the word. A simple approach is to add a click handler like the following to an HTML element that contains the word and the definition.

function clickWord() {
  if (this.box.className.indexOf('visible') == -1) {
    this.box.className = 'wordBox visible';
  } else {
    this.box.className = 'wordBox';
  }
}

The definition can have the style display: none by default, and you can have a CSS rule that applies display: block to elements inside .visible elements.

You can add such a click handler to every element that has a certain class name by using getElementsByClassName().

The following snippet demonstrates this approach. It both shows the definition and selects the text of the definition when you click on the word.

function selectText(element) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNodeContents(element);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
  }
}

var autoHide = false,
    autoHideSeconds = 1;

function clickWord() {
  var box = this.box;
  if (box.className.indexOf('visible') == -1) {
    box.className = 'wordBox visible';
    selectText(this.definition);
    if (autoHide) {
      window.setTimeout(function () {
        if (box.className.indexOf('visible') != -1) {
          box.className = 'wordBox';
        }
      }, autoHideSeconds * 1000);
    }
  } else {
    box.className = 'wordBox';
  }
  
}

window.onload = function () {
  var boxes = document.getElementsByClassName('wordBox');
  for (var i = 0; i < boxes.length; ++i) {
    var box = boxes[i],
        word = box.getElementsByClassName('word')[0];
    word.box = box;
    word.onclick = clickWord;
    word.definition = box.getElementsByClassName('definition')[0];
  }
};
body {
  font-family: sans-serif;
}

.wordBox {
  margin: 20px 0;
}

.word {
  cursor: pointer;
  padding: 4px 8px;
  border: 2px solid #888;
  border-radius: 5px;
  color: #333;
}
.word:hover {
  border-color: #444;
  color: #000;
}

.definition {
  display: none;
}

.visible .definition {
  display: block;
  padding: 8px;
  margin-top: 5px;
  color: #000;
  background-color: #cde5dd;
}
<div class="wordBox">
  <span class="word"> Platinum </span>
  <div class="definition"> Platinum is a chemical element with symbol Pt and atomic number 78. It is a dense, malleable, ductile, highly unreactive, precious, gray-white transition metal. Its name derives from the Spanish word <i>platina</i>, meaning "little silver". </div>
</div>

<div class="wordBox">
  <span class="word"> Gold </span>
  <div class="definition"> Gold is a chemical element with symbol Au and atomic number 79. In its purest form, it is a bright, slightly reddish yellow, dense, soft, malleable and ductile metal. Chemically, gold is a transition metal and a group 11 element. </div>
</div>

<div class="wordBox">
  <span class="word"> Silver </span>
  <div class="definition"> Silver is a chemical element with symbol Ag and atomic number 47. A soft, white, lustrous transition metal, it possesses the highest electrical conductivity, thermal conductivity and reflectivity of any metal. Most silver is produced as a byproduct of copper, gold, lead, and zinc refining. </div>
</div>

<div class="wordBox">
  <span class="word"> Copper </span>
  <div class="definition"> Copper is a chemical element with symbol Cu (from Latin: cuprum) and atomic number 29. It is a ductile metal with very high thermal and electrical conductivity. Pure copper is soft and malleable; a freshly exposed surface has a reddish-orange color. It is used as a conductor of heat and electricity, a building material, and a constituent of various metal alloys. </div>
</div>

<div class="wordBox">
  <span class="word"> Aluminum </span>
  <div class="definition"> Aluminum is a chemical element in the boron group with symbol Al and atomic number 13. It is a silvery-white, soft, nonmagnetic, ductile metal. Aluminum is the third most abundant element (after oxygen and silicon) in the Earth's crust, and the most abundant metal there. It makes up about 8% by weight of the crust, though it is less common in the mantle below. </div>
</div>
Michael Laszlo
  • 11,163
  • 2
  • 26
  • 45
  • Hi Michael, thank you so much! This is really awesome! By the way, is there a way to prevent the box from expanding. If that is not possible, is there a way to set the box to collapse after a set period of time? As much as possible, I don't want it to be expanded all the time to save space and scrolling time. Thanks! – JAMES Dec 01 '15 at 13:37
  • The box must be displayed to select the text within it. It is possible to automatically hide the box, though. I've added a variable called `autoHide` to the code snippet above. If its value is `false`, the box only goes away if you click on the word a second time. If you set `autoHide` to `true`, the box automatically goes away after a number of seconds that you can configure with the variable `autoHideSeconds`. – Michael Laszlo Dec 23 '15 at 01:04