How to Make VAR a Hyperlink in JavaScript
The word “hyperlink” is the more formal, long-form term for a “link” on a Web page. Anchor tags use URLs – the address of a document on the Web – to create links in HTML. These links are static, but you can also put HTML links together inside scripts using JavaScript. By setting the URL of a link to a variable, you give that URL a reusable name and can call it within other parts of the script. Combining the variable and HTML creates the link, which you can append to any pair of tags on the page.
Instructions
-
-
1
Open your Web page in an editor so you can view and edit its code. Scroll to the bottom of the code and find the closing “</body>” tag. Above that tag, add a pair of “<script>” tags:
<script type=”javascript/text”>
</script>
</body> -
2
Write a line of JavaScript that declares a variable and sets its value to a URL. JavaScript code goes between the “<script>” tags:
var myURL = “http://yourdomain.com/path/to/file.html”;
-
-
3
Declare a second variable and set its value to a string that contains anchor tag code for a link. Inside the anchor tag code, break the string so you can place the first variable inside the “href” attribute. Breaking the string for a variable – known as “concatenation” – is accomplished with plus signs. Since the anchor tag requires quotation marks for “href,” use single quotes around the HTML code:
var myLink = '<a href=”' + myURL + '“>' + myURL + '</a>';
This example calls the “myURL” variable twice: once for the “href” attribute and a second time for the link text.
-
4
Scroll up in your page code and look for the tags where you want to add or output the link. This can be an empty div, for example. Give the opening tag an ID name if it does not already have one:
<div id=”output_link”></div>
-
5
Go back to your JavaScript and add this line:
document.getElementById(“output_link”).appendChild(myLink);
The “document.getElementById()” portion of this code finds an “element” on the page, created by HTML tags, by its ID name. The “appendChild” portion appends new content to the element by inserting a “child” element inside, so the effect is placing the links within a set of tags. Since the variable “myLink” contains HTML and JavaScript code that builds the link, you can place that inside “appendChild().”
-
1