kmmbify
kmmbify

Reputation: 13

Add link to image in javascript

I'm replacing one image with another in javascript, then adding a link to it, but it doesn't seem to be working. Any suggestions?? Please and thank you!!

function showImage2(){
    document.getElementById("tbc").src = "images/s2.jpg";
var elem = document.getElementById("Slideshow");
    elem.style.display = "none";
    document.getElementById('tbc').style.display='block';
document.getElementById('tbc').style.usemap='ss2Map'; 
var link = document.createElement('a'); // create the link
    link.setAttribute('href', 'wastewater.html'); // set link path
    link.appendChild("images/s2.jpg"); // append to link
}

Upvotes: 1

Views: 6866

Answers (3)

Xzigraz
Xzigraz

Reputation: 103

I think all you really need is to have one image with a link and one image without the link. Onload, the image without the link is shown and the other image with the link is hidden. Once click on a button or something, then hide the image without the link and show the image with the link correct?

<img id="image1" src="http://us.123rf.com/400wm/400/400/tonygers/tonygers1108/tonygers110800022/10200687-manipulated-nasa-photographs-of-the-earth-and-moon-isolated-together-on-a-black-background.jpg" />
<a style="display:none;" id="image2" href="http://www.google.com" target="_blank"><img  src="http://d1jqu7g1y74ds1.cloudfront.net/wp-content/uploads/2011/08/us-astronaut-bruce-mccandless-space-walk.jpg" /></a>
<a href="javascript:void(0)" onclick="showImage2()">Click Me</a>
<script>
    function showImage2(){
        var imageOne = document.getElementById('image1');
        var imageTwo = document.getElementById('image2');
        imageTwo.style.display = 'block';
        imageOne.style.display = 'none';
    }   
</script>

You can see the working code here. http://jsfiddle.net/QbbJU/1/

Upvotes: 1

Jnatalzia
Jnatalzia

Reputation: 1687

link.appendChild("images/s2.jpg"); // append to link

This line won't do anything. You can only append an element, not a text string. You need to append document.getElementById("tbc") instead if I understand your markup correctly.

If that's not what you're trying to append, you can use var el = document.createElement('img') to create an img tag and then set the src attribute using el.setAttribute('src','images/s2.jpg')

After this, the above line would become link.appendChild(el); which would work.

Upvotes: 2

SLaks
SLaks

Reputation: 887453

appendChild() can only take a DOM node, not a string.

To set the text of an element, you can either set innerHTML or textContent, or append a text node (from document.createTextNode())

You also probably want to put the link somewhere in your page.

Upvotes: 0

Related Questions