user1433767
user1433767

Reputation: 665

Javascript dynamic link issues?

There might be a duplicate of this (I've tried checking questions on creating dynamic links but they reference a static link - I want this link to be hidden from the user). On testing the following code on the ww3 site:

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
document.write("<a href=&quot;www.google.com&quot;>Google</a>");
</script>

</body>
</html>

I get:

 http://www.w3schools.com/jsref/%22www.google.com%22

As the link address rather than www.google.com.

How do I correct this problem? And how do I make it so the link only appears after a set time? Note, this is a simplified version of the code for readability (the dynamic link will including two floating point variables assigned at the time the script is run).

Upvotes: 1

Views: 201

Answers (4)

Michael Berkowski
Michael Berkowski

Reputation: 270609

An <a> tag's href must include the protocol http://, otherwise it links to a document relative to the page the link is on:

// Print quote literals, not html entities `&quot;`
document.write("<a href='http://www.google.com'>Google</a>");

The use cases for document.write() are often limited since it can't be used after the page has loaded without overwriting the whole thing. A lot of the time you will want to create the element after the page has already rendered. In that case, you would use document.createElement() and appendChild().

// Create the node...
var newlink = document.createElement('a');
newlink.href = 'http://www.google.com';
// Set the link's text:
newlink.innerText = "Google";

// And add it to the appropriate place in the DOM
// This just sticks it onto the <body>
// You might, for example, instead select a specific <span> or <div>
// by its id with document.getElementById()
document.body.appendChild(newlink);

By the way, w3schools is not affiliated with the W3C, and their examples are generally not recommended since they are often out of date or incomplete.

Upvotes: 3

tptcat
tptcat

Reputation: 3961

You have 2 issues:

1) You need http:// before the URL so it's: http://www.google.com 2) You don't need to use quotes in document.write, but if you want to you can do one of these 3:

document.write('<a href="http://www.google.com">Google</a>');
document.write("<a href='http://www.google.com'>Google</a>");
document.write("<a href=http://www.google.com>Google</a>");

Upvotes: 2

Douglas
Douglas

Reputation: 37763

To make the link absolute, include the "http://" at the start of the url. Write out:

<a href="http://www.google.com">

instead of

<a href="www.google.com">

The second example will be treated as a relative url, like index.html for example.

Upvotes: 0

svanryckeghem
svanryckeghem

Reputation: 923

Use the slash "\" to escape the quote

Upvotes: 1

Related Questions