Change image source with JavaScript

Alvaro Arregui picture Alvaro Arregui · Sep 5, 2011 · Viewed 311.7k times · Source

So I'm new with JavaScript (this is actually my first attempt to make something work) and I'm having a bit of trouble. I thought I had enough knowledge to make this work, I've even googled for tutorials and scripts that could help me work this out but nothing really helped.

I can't seem to change the image source, heres the code that I have so far:

    function changeImage(a) {
        document.getElementById("img").src=a.src;
    }
    <div id="main_img">
        <img id="img" src="1772031_29_b.jpg">
    </div>
    <div id="thumb_img">
        <img src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg");'>
        <img src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg");'>
        <img src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg");'>
    </div>

Could anyone please explain if I'm doing something wrong? Or maybe I'm missing something? Help me please :-)

Answer

user180100 picture user180100 · Sep 5, 2011

function changeImage(a) so there is no such thing as a.src => just use a.

demo here