dave
dave

Reputation: 481

How do i add an image to an element using javascript

I basically have this link, where when i click it, i want an image to show over it. Using javascript how can i do this?

<a> click me </a>

css:

a.clicked
{
   /*what goes here?*/
}

Upvotes: 2

Views: 1387

Answers (4)

RobG
RobG

Reputation: 147363

Adding a new image element is pretty easy:

// Append an image with source src to element
function appendImage(element, src, alt) {
  // DOM 0 method
  var image = new Image();

  // DOM 1+ - use this or above method
  // var image = document.createElement('img');

  // Set path and alt properties
  image.src = src;
  image.alt = alt;

  // Add it to the DOM
  element.appendChild(image);

  // If all went well, return false so navigation can 
  // be cancelled based on function outcome
  return false;
}

so in an A element:

<a onclick="appendImage(this, 'foo.jpg', 'Picture of foo');">Add an image</a>

If the A is a link and you wish to cancel navigation, return whatever the function returns. If the function doesn't return false, the link will be followed and should provide equivalent functionality:

<a href="link_to_picture or useful page" onclick="
  return appendImage(this, 'foo.jpg', 'Picture of foo');
">Add an image</a>

Upvotes: 3

McKayla
McKayla

Reputation: 6949

First, you'll probably want to give the link an ID.

<a id="click-me">Click me!</a>

Then for the JavaScript..

document.getElementById('click-me').addEventListener('click', function () {
    var image = new Image();
    image.src = "your-picture.jpeg/png/whatever";
    this.appendChild(image);
});

Upvotes: 0

AjayR
AjayR

Reputation: 4179

You should use like this. There are several other good methods, this is just for simplicity and understanding purpose

<body>
<a onClick='ChangeImage(this);return false'> Click Me <a>
</body>


<script>
function ChangeImage(obj)
{
 obj.innerHTML = "<img src='imangename.jpg'>";
}
</script>

Upvotes: 1

benck
benck

Reputation: 2052

The javascript plugin you may need is Highslides, Check here for examples.

Download highslides here.

Upvotes: 0

Related Questions