0
function on_click(e)
{
  if( !e ) e = window.event;
   dragok = false;
   document.onmousemove = null;
   var x = e.target||e.srcElement;
  if( dx > 200 ) // dx is the numbers of pixels from leftside of mouse pointer
    {
      // document.write(dx); this is working it prints dx value but unable to create an image        
      var img = IEWIN ? new Image() : document.createElement('img');
      img.src="cool.jpg";
      document.getElementById(x.id).appendChild(img);
    }
 }

I found these snippet on Stack Overflow but not working when I tried it . Here it is What is the best JavaScript code to create an img element.

The aim is to create an image when function on_click is called, (function on_click is called for onclick event). dx is the pixels measured from the left side. So if the Mouse pointer is greater than 200 pixels and if the mouse is clicked, It should create an image at that place I mean if dx is 206 then an image should be created with the distance of 206 pixels, but I'm unable to make create an image element with JavaScript.

What changes I have to make in JavaScript code?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
niko
  • 9,285
  • 27
  • 84
  • 131

1 Answers1

1

All you need is this for all browsers:

var img = new Image();
img.src = "cool.jpg";
img.className = "myClass";
img.id = "mainImage";
x.appendChild(img);

If you already have the DOM element, there's no reason to get the id and then do document.getElementById(x.id). Just use x directly.

To use CSS rules that refer to this image, you would make rules like this (depending upon whether you're referring to the class or the id):

.myClass {border: 1px solid #F00;}
#mainImage {padding: 14px;}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • absolutely working ! so the modern browsers dont support document.createelement? Could you tell me how to create the width and height properties of it. I mean can I set img.id to it and also set properties to it in css sheet? But cant we just append do we need to mention parent node always? – niko Sep 18 '11 at 06:38
  • no jfriend I want to create img.id or img.class for the created img tag by javascript and then reference its properties using css sheet can i do that ? – niko Sep 18 '11 at 06:47
  • I added a couple more lines to my example to show you adding a class name and an id that you can refer to with CSS rules. An Image object is a DOM element. I presume you can use `document.createElement()` instead, but why? The `new Image()` syntax is built in. – jfriend00 Sep 18 '11 at 06:59
  • ok how do i refer it in css I have used img.myclass { some properties } but not working is that right? – niko Sep 18 '11 at 07:19
  • I add a couple CSS rules to my answer. – jfriend00 Sep 18 '11 at 07:25