Change image source with JavaScript


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) {
    <div id="main_img">
        <img id="img" src="1772031_29_b.jpg">
    <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");'>

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

This question is tagged with javascript image onclick src

~ Asked on 2011-09-05 20:40:38

The Best Answer is


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

demo here

~ Answered on 2011-09-05 20:41:45


If you will always have the pattern on _b instead of _t you can make it more generic by passing reference to the image itself:


Then in the function:

function changeImage(img) {
    document.getElementById("img").src = img.src.replace("_t", "_b");

~ Answered on 2011-09-05 20:43:33

Most Viewed Questions: