2

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?*/
}
3
  • You can't add an image over something using CSS. Commented May 25, 2011 at 3:48
  • gotcha. but how can i add an element using javascript? Commented May 25, 2011 at 3:49
  • Oh. Ok. Yeah. You can do that. But adding a 'clicked' class to the link won't do anything. Commented May 25, 2011 at 3:55

4 Answers 4

3

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

2 Comments

how do you make the image stay there after user clicks on the link?
the image will stay, but it will overwrite when you click again.
0

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

Download highslides here.

Comments

0

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);
});

2 Comments

how do you make the image stay there after user clicks on the link?
It should stay there until they reload the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.