micoco
micoco

Reputation: 299

Display element of array onclick

This code displays the content of JSON file by formatting every word into sentences and then into HTML. On mouseover, words become blue. On click they become red. The next thing I want to do is to display the translation of the words (already in the json array) onclick.

https://jsfiddle.net/ve64qvtm/

  var json = [
    [
      ["Peki", "Well"],
      ["nedir", "what"],
      ["bu", "it"],
      ...
    ]
  ];
  var arr2 = [];
  for (k = 0; k < json.length; k++) {
    var arr = json[k];
    arr2.push('<p>');
    for (i = 0; i < arr.length; i++) {
      if (arr[i][0].length == 1) {
        arr2.push(arr[i][0]);
      } else {
        arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
      }
    }
    arr2.push('</p>');
  }
  document.getElementById("text").innerHTML = arr2.join('');

  var words = [...document.getElementsByClassName("word")];
  words.forEach(function(word) {
    word.onclick = function() {
      if (word.className == "clicked") {
        word.className = 'notclicked';
      }
      if (word.className == "onmouse") {
        word.className = 'clicked';
      }
    }
    word.onmouseover = function onMouse() {
      if (word.className != "clicked") {
        word.className = 'onmouse';
      }
    }
    word.onmouseout = function onMouse() {
      if (word.className != "clicked") {
        word.className = 'notclicked';
      }
    }
  });

I have no idea how to do this as the text to display is a variable. How am I supposed to do this?

Upvotes: 0

Views: 426

Answers (1)

Omar Yafer
Omar Yafer

Reputation: 853

How about using Twitter Bootstraps tooltip. Add jQuery, bootstraps JS and CSS; once all this is added you would need to edit the line

arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');

To something like

arr2.push(' <span class="notclicked word ' + i + '" data-toggle='tooltip' data-placement='top' title='YOUR_TRANSLATION_HERE'>' + arr[i][0] + '</span>');

EDIT 2 - Updated Link:

Here is a working example

Edit 3

I Would also add a bit of margin on top and bottom so that you don´t get unexpected behaviour from the tooltips, just because there is no space.

Upvotes: 1

Related Questions