Add Word Links to a Text

Asked

Viewed 1,088 times

1

On an html page how to make the words of the text be converted into links? so that when clicking on a given word, open the google page with the word translation.

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

If you click universe opens

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

  • You want to create a link to all the words in the text: "The", "Universe", "is", "to", "Everyone"?.. if not, what criteria to be adopted?

  • And if you have a dot, a comma... so you would need to define a criterion and apply only the link to words from a list of predetermined words.

  • @sam this, for all words separately, has to see also that should disregard numbers and punctuation. I will test the proposed answers here

  • 1

    Does it only serve word for word? I made an example that can be what is selected,,

  • Show Leo, it is interesting this option too, thank you!

4 answers

2

A solution is:

  • divide text into words with split
  • take all words and turn into a link with map
  • put everything back together with join
  • apply the 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>

2


Explanation:

create ink

  1. Receives a word and inserted in a Templete String from a tag to

creatArrayDeLinks

  1. Take the element text using textContent
  2. Performs a separation of the string by space, transforming to an array using the .split()
  3. Filters the array by removing empty positions or line breaks with .filter()
  4. Maps our word array to an array of tags using the method create ink using the prototype .map()

create LinksEmElements

  1. I create an array called tags that will receive our links and child elements in string format
  2. Receives the parent element verifying if the nodetype is 3(Text)
  3. If your nodetype NAY for 3(Text) it checks if it has child elements and if they are type 3(Text) if it does not create a recursiveness calling to himself.
  4. If nodetype is 3(Text) call the function creatArrayDeLinks that returns an array to me
  5. I perform array unstructuring using the spread Operator from the es6 to assign it to the array tags directly.
  6. I check if the array contains something
  7. If it contains its clean parent element with the innerHTML
  8. Join the array in a string separating by space using the .Join
  9. Finally I assign the string in the div again using the innerHTML to convert text to html

create

  1. Selects the appropriate element with querySelector
  2. I call the function create LinksEmElements 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>

  • 1

    I even thought I would be negative by the question, but your answer is mass, I will test. Thank you very much!

  • 1

    Marcos, in this case it does not return the html in the layout it was before, that is, it removes the paragraphs and all html tags, leaving the text without any layout formatting

  • 1

    I believe I would have to consider at least the paragraphs

  • 1

    @Miguelsilva I don’t know if it will help but this one I had commented.

  • Marcos, when a word starts with quotation marks (") it does not receive the link correctly, until I tried to solve, but I could not, know how to solve?

2

My solution is to create a link with/the selected words/words.

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

Unfortunately here when running the example, the link created at the top of the text only opens if right-clicking and selecting open in new tab or window.

But the server opens by clicking directly on 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 -->
   
  • I tested in the exemplo funcional that gave and only opens if right click mouse

  • @Miguelsilva, which browser?

  • Firefox 61.0.1 Quantum

  • @Miguelsilva, it’s true, a lot doesn’t work in firefox. Bad browser

  • True and has worsened with every version

  • But your script helped me in another project that intended to copy a selected text to share, kkkk vlw same

  • 1

    @Miguelsilva tested here with all browsers, only firefox left to be desired

Show 2 more comments

0

You can create a javascript function to open a new tab and receive 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.