...

View Full Version : document.write alternative



TrainReq
07-11-2007, 08:57 PM
I want to exicute the following code on the page using a .js file:


<a href=http://www.site.com>
<img src="http://www.site.com/blah.gif" style="position:absolute; left:0px; top: 0px;" border="0"> </a>

but everytime I use
document.write('<a href="http://www.site.com><img src="http://www.site.com/blah.gif" style="position:absolute; left:0px; top: 0px;" border="0"> </a>')

It redirects/makes the page blank with just that code on it... I even tried putting a void on the code, and that didnt help either. Is there an alternative to document.write?

felgall
07-11-2007, 09:09 PM
The best way is to use the appropriate DOM commands to add the new content.

The other (easier) way is to use document.innerHTML

_Aerospace_Eng_
07-11-2007, 09:15 PM
There are a few ways you can do this. document.write is not one of them.
1) Add this to the page

<a href="http://www.site.com" id="jslink" style="display:none;">
<img src="http://www.site.com/blah.gif" style="position:absolute; left:0px; top: 0px;" border="0"> </a>
Then in the javascript

<script type="text/javascript">
window.onload = function()
{
document.getElementById('jslink').style.display = 'inline';
}
</script>
2) Which may the be the route you are more likely to take as it doesn't require that you add to the html.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
if (oldonload)
{
oldonload();
}
func();
}
}
}

addLoadEvent
(
function()
{
var createLink = document.createElement('a');
createLink.setAttribute('href','http://www.site.com');
createLink.setAttribute('id','jslink');
var createImg = document.createElement('img');
createImg.setAttribute('src','http://www.site.com/blah.gif');
createImg.style.border = '0';
createLink.appendChild(createImg);
document.getElementsByTagName('body')[0].appendChild(createLink);
document.getElementById('jslink').style.position = 'absolute';
document.getElementById('jslink').style.top = '0';
document.getElementById('jslink').style.left = '0';
}
)
</script>
</head>

<body>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum