Bai Lor
Bai Lor

Reputation: 1

Onclick Javascript Function to adding image

I am trying to add a function that when a customer click on the small thumbnail, it adds an image. see code below.

<html>
<head>

<script type="text/javascript">
<!--

function addimage2() { 
      var img = document.createElement("img");
      img.src = "swatch.jpg"; 
      img.height = 75; 
      img.width = 113;
      img.style.top=800;
      img.style.right=100;
      document.body.appendChild(img);
    }



//-->
</script>
</head>
<body>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
       <td width="43%" rowspan="2"><img src="tuffet-diagram.jpg" width="270" height="326"></td>
      <td width="57%" height="162">Zone 1:</td>
   </tr>
  <tr>
      <td>Zone 2: </td>
  </tr>
  <tr>
     <td colspan="2">Zone 1 color:
     <img src="swatch-sm.jpg" alt="swatch-sm" onClick="addimage2();"></td>
  </tr>
  <tr>
     <td colspan="2">Zone 2 color:</td>
  </tr>
</table>
</body>
</html>

it keeps adding next to the thumbnail and not where the specify location such as when a customer click on Zone1 swatch, it should add to the Zone 1 area, etc.

here's the link to my page: http://www.manufacturingsolutionscenter.org/salma/tuffet-color.html

Thank you.

Upvotes: 0

Views: 10228

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Try this :

function addimage2(where) { 
  var img = document.createElement("img");
  img.src = "swatch.jpg"; 
  img.height = 75; 
  img.width = 113;
  img.style.top=800;
  img.style.right=100;
  where.parentNode.appendChild(img);
}

and

<img src="swatch-sm.jpg" alt="swatch-sm" onClick="addimage2(this);">

The idea is to provide the location where the new image must be added in the function call.

Upvotes: 0

John Fisher
John Fisher

Reputation: 22719

This code:

document.body.appendChild(img)

determines where the image goes. You'll need to figure out which element should get the image appended to it and place it there instead.

BTW, this type of document manipulation is immensely easier if you use JQuery.

Upvotes: 0

Surreal Dreams
Surreal Dreams

Reputation: 26380

The script is doing exactly what you're instructing it to do - appending the new image to the body of the document: document.body.appendChild(img);

This literally means, "append this new element as a child of the body tag." That places the new tag just before </body>. If you want to add the new image elsewhere, target the precise location you want it added.

Upvotes: 1

Related Questions