faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

39 of 47 people (83%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I dynamically add an IMG element to a page?
How can I dynamically add an IMG element to a page?

Apr 3rd, 2000 08:14
Martin Honnen, Linh Le,


NN6 and IE4+ can insert new elements in the page, NN4 can only add 
layers though if you add them to the end of the document it kind of 
looks as if you inserted them into the document as with IE4+ and NN6. 
The following gives an example where in IE4+ the IMG elements HTML is 
inserted into the document body, in NN6 the IMG element is created and 
then appended to the document body and in NN4 a layer containing an IMG 
is created and positioned at the end of the document:

<HTML>
<HEAD>

<SCRIPT>
var imgURL = 'whatever.gif';
var img = new Image(); 
img.src = imgURL;
var left, topPos;
function addImage () {
  if (document.all)
    document.body.insertAdjacentHTML('beforeEnd',
      '<IMG SRC="' + img.src + '">');
  else if (document.createElement) {
    var imgEl = document.createElement('IMG');
    imgEl.src = img.src;
    document.body.appendChild(imgEl);
  }
  else if (document.layers) {
    var l = new Layer(img.width);
    if (typeof left == 'undefined' || left + img.width > 
window.innerWidth) {
      left = 0;
      topPos = document.height;
      document.height += img.height;
    }
    else 
      left += img.width;
    l.left = left;
    l.top = topPos;
    l.document.open();
    l.document.write('<IMG SRC="' + img.src + '">');
    l.document.close();
    l.visibility = 'show';
    if (l.left + l.clip.width > document.width)
      document.width += img.width;
  }
}
        
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript: addImage(); void 0">
add image
</A>
<BR>
</BODY>
</HTML>