Add links to words in a text

1

On an html page how do the words in the text be converted into links? so that by clicking on a certain word, open the google translate page with the translation of the word.

For example, in this sentence:

"The universe is to everyone"

If the user clicks me "The" will open the link

https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/The

Clicking% with% opens

universe

    
asked by anonymous 19.07.2018 / 22:07

4 answers

2

Explanation:

createLink

  • You receive a word and insert it into a Temple String of a tag a
  • createArrayDeLinks

  • Get element text using textContent
  • Performs a string separation by space, transforming an array using .split ()
  • Filters the array by removing empty positions or breaking lines with .filter ()
  • Map our word array to an array of tags using the createLink method using prototype .
  • createLinksEmElements

  • I create an array called tags that will receive our links and child elements in the string format
  • Receives the parent element verifying that the nodeType is 3 (Text)
  • If your nodeType NOT is 3 (Text) it checks if it has child elements and if they are of type 3 (Text) otherwise it creates a recursivity calling itself.
  • If the nodeType is 3 (Text) call the function createArrayDeLinks that returns an array
  • Perform array de-structuring using es6 operator spread to assign it to array tags directly.
  • Check if the array contains something
  • If you contain your parent element with innerHTML
  • Put the array in a space separating string using .join
  • Finally assign the string to the div again using the innerHTML to convert the html text
  • createTextClick

  • Select the appropriate element with querySelector
  • I call the function createLinksEmElements passing the result obtained in the previous step
  • var criarLink = t => '<a target="_blank" href="https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/${t}">${t}</a>'
    
    var criarArrayDeLinks = e => e.textContent.split(' ').filter(i => i !== '' && i !== '\n').map(i => criarLink(i));
    
    function criarLinksEmElementos(pai) {
      const tags = [];
    
      if (pai.nodeType == 3 && pai.textContent.trim()) { 
        tags.push(...criarArrayDeLinks(e));
      } else {          
        pai.childNodes
           .forEach(
              e => {         
                if (e.nodeType == 3 && e.textContent.trim()) { 
                  tags.push(...criarArrayDeLinks(e));
                } else {          
                  tags.push(criarLinksEmElementos(e).outerHTML);
                }
            });
      }
      
      if (tags.length) {    
        pai.innerHTML = tags.join(' ');    
      }
    
      return pai;  
    }
    
    function criarTextoClicavel(seletor) {  
      const div = document.querySelector(seletor);
      criarLinksEmElementos(div);
    }
    
    criarTextoClicavel('#texto-clicavel');
    /* caso queria remover o efeito do link */
    a {
      text-decoration: none;
      color: black;
    }
    <div id="texto-clicavel">
      <p>
        The universe is to everyone
      </p>
      <p>
        The <b>universe</b> is to <i>everyone</i>
      </p>
    </div>
        
    19.07.2018 / 22:59
    2

    One solution is:

    • split text into words with split
    • pick up all words and make a link with map
    • put it all together again with join
    • Reapply new text as html in the right place

    Example:

    function aplicaLink(texto){
      return '<a href="https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/${texto}">${texto}</a>';
    }
    
    const divTexto = document.getElementById("div1");
    divTexto.innerHTML = divTexto.innerHTML.split(' ').map(aplicaLink).join(' ');
    <div id="div1">The universe is to everyone</div>
        
    19.07.2018 / 22:39
    2

    My solution is to link to the selected word / words.

    • getSelection () - Returns a Selection object representing the part of the text selected by the user. I put this in a variable to concatenate the link.
      

    Unfortunately here while running the example, the link created at the top of the text only opens if you right-click and select open in new tab or in a new window.

         

    But on the server opens directly by clicking the link created

    JavaScript

       function showSelection() {
         document.getElementById('demo').innerHTML = document.getSelection();
         var variavel=document.getElementById('demo').innerHTML;
         if (variavel!=""){
            //o texto do link         
            document.getElementById("demo").text = "Traduzir texto selecionado";
            //o atributo href do link         
            document.getElementById("demo").setAttribute("href", "https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/"+variavel);
         }
    
      }
    
      document.captureEvents(Event.MOUSEUP)
    
      document.onmouseup = showSelection
    

    HTML

    <a id='demo' target='_blank' href=''></a>   
    
    <!-- daqui para baixo coloque seu HTML -->
    
        
    20.07.2018 / 01:23
    0

    You can create a javascript function to open a new tab and get the word you want to translate.

    function abrePagina(palavra){
       window.open("https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/"+palavra ,"_blank");  
    }
    

    With the function you need to add the click event to each word you want to translate.

        
    19.07.2018 / 22:17