Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a line of text generated in a javascript file into a clickable link in HTML

Sorry for the incredibly lame question, but as a brand new programmer all the answers I've found while searching all day are for other problems not specific to me so I decided I'd post about it.

I have taken it upon myself to convert a sample "Random Quote Generator" program I found into a small web based app that can produce random links at the touch of a button, but as I soon found out just replacing the example quotes with the links of my choice only produced normal un-clickable text.

I have tried many things relating to messing with the div's and the id tags but nothing works for me.

My code for the html is as follows:

<html>
<head>
    <title>Simpsons Episode Generator</title>
</head>
<body>
    <h1>Simpsons Episode Generator</h1><br>
    <img src="https://vignette2.wikia.nocookie.net/simpsons/images/9/97/Mr_Burns_-_the_box.jpg/revision/latest?cb=20121215235014" alt="Mr Burns box">

    <div id="linkDisplay">
        <!-- Link will pop up here -->
    </div>

    <!-- Button to call the javascript and prduce a link -->
    <button onclick="newLink()">New Episode</button>

    <!-- javascript declared -->
    <script src="javascript.js"></script>
</body>
</html>

So as you can see, it just calls the javascript to run the randomiser then prints the result.

The javascript is as follows:

//Links To Episodes
var links = [
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-1/',
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-2/',
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-3/',
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-4/',
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-5/',
    'http://kisscartoon.so/episodes/the-simpsons-season-1-episode-6/'
];

//Select 1 Link at random and push it to the HTML
function newLink() {
    var randomLink = Math.floor(Math.random() * (links.length));
    document.getElementById('linkDisplay').innerHTML = links[randomLink];
}

All i want is to just make the click the HTML is receiving after the button is pressed to be clickable.

Thanks for reading and sorry for asking such a simple sounding question but i really have been looking all day how to do it by myself...

like image 926
Kevin Avatar asked Sep 11 '17 00:09

Kevin


1 Answers

If you want to navigate to that URL, you don't need to "click the link", you can just change the location of the window:

window.location.href = links[randomLink];

If you want to make a link to that location, so people can click it, make that <div> an <a>

<a id="linkDisplay" href='#' />

(the # means it will just go to the top of the page) and then update the href as needed:

document.getElementById('linkDisplay').href = links[randomLink];
like image 185
Ben Avatar answered Sep 30 '22 09:09

Ben