Jay
Jay

Reputation: 64

Turn Array Index into an Hyperlink

I am importing a text document named test.txt using JavaScript and sending each line into an array called linesArr. I am successful doing that but I need to turn the array indexes into a clickable hyperlink using JavaScript only. (I'm using Animate CC but JavaScript solutions work the same in Animate CC.

My text file reads (each on separate lines)

 https://www.google.com
 https://www.facebook.com
 https://www.amazon.com

JavaScript

that = this;

function getData(){
   var xmlhttp;

   if (window.XMLHttpRequest) {
       xmlhttp = new XMLHttpRequest();               
   }           
   else {               
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
   }

   xmlhttp.onreadystatechange = function () {               
       if (xmlhttp.readyState == 4) {                   
         var lines = xmlhttp.responseText;

         intoArray(lines);                 
       }               
   }

   xmlhttp.open("GET", "test.txt", true);
   xmlhttp.send();    
 }

 function intoArray (lines) {
    var lineArr = lines.split('\n');
    alert("lineArr[2]");
 }

 getData();

 that.button.addEventListener("click", fl_ClickToGoToWebPage);

 function fl_ClickToGoToWebPage() {
     window.open(lineArr[1], "_blank");
 }

Upvotes: 0

Views: 67

Answers (1)

Miika OK
Miika OK

Reputation: 60

Your links are not stored in the correct format. Any correctly formatted hyperlinks must include the scheme part of the URL. Try adding the scheme (HTTP:// or the HTTPS://) to the links listed in the text file. Most of the websites do have HTTPS, at least they should have for security reasons.

Like this:

If you can't add the scheme parts directly to the text file, you can try adding them using JavaScript.

window.open("https://" + lineArr[1], "_blank");

To create a hyperlink using JavaScript you can either append HTML to an existing element or try creating a new one. Here is something you might get it working with http://jsfiddle.net/rD6BZ/

You can create a valid hyperlink element with JavaScript like this:

var hyperlink = '<a href="https://www.google.com">Link</a>';

Upvotes: 1

Related Questions