Alvaro Arregui
Alvaro Arregui

Reputation: 609

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) {
        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 :-)

Upvotes: 36

Views: 393151

Answers (12)

Fethi Pounct
Fethi Pounct

Reputation: 1299

first we have this image1 displayed:

<input id="img_prod" type="image" src="img/image1.png" height="400" width="400"
                            onclick ="location.href=this.src">

onclick to display the image full screen

and we have other image2

<input type="image" src="img/image2.png" height="75" width="75"
                 onclick="document.getElementById('img_prod').src = this.src;">

onclick we replace image1 by image2

Upvotes: 0

John Doe
John Doe

Reputation: 31

I know this question is old, but for the one's what are new, here is what you can do:

HTML

<img id="demo" src="myImage.png">

<button onclick="myFunction()">Click Me!</button>

JAVASCRIPT

function myFunction() {
document.getElementById('demo').src = "myImage.png";
}

Upvotes: 1

Tracker1
Tracker1

Reputation: 19344

Your only real problem is you are passing a string, not an object with a .src property

Some suggestions:

  • Use a naturally clickable element trigger, such as <button>
  • Use data- prefixed attributes for event data on the element
  • Use late bound events when the DOM is ready.

Markup:

<div id="main_img">
  <img id="img" src="1772031_29_b.jpg">
</div>
<ul id="thumb_img">
  <li><button data-src='1772031_29_b.jpg'><img src='1772031_29_t.jpg' /></button></li>
  <li><button data-src='1772031_55_b.jpg'><img src='1772031_55_t.jpg' /></button></li>
  <li><button data-src='1772031_53_b.jpg'><img src='1772031_53_t.jpg' /></button></li>
</ul>

JavaScript:

If you need to support IE and other legacy browsers, Use a proper polyfill for Array.from

function clickedButton(btn, event) {
  document.getElementById('img').src = btn.getAttribute('data-src');
}

function bindClick(btn) {
  btn.addEventListener('click', clickedButton.bind(null,btn));
}

// Setup click handler(s) when content is loaded
document.addEventListener("DOMContentLoaded", function(){
  Array.from(document.querySelectorAll('#thumb_img > button'))
    .forEach(bindClick));
});

Edit: Vanilla JS for modern browsers.

Upvotes: 5

qwerty helper
qwerty helper

Reputation: 21

The problem was that you were using .src without needing it and you also needed to differentiate which img you wanted to change.

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

Upvotes: 2

Palak Jain
Palak Jain

Reputation: 37

Instead of writing this,

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a.src;
}
</script>

try:

<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a;
}
</script>

Upvotes: 1

user7338225
user7338225

Reputation: 11

The Following Example Program used to change the image src attribute for every 100 milliseconds. you may call the given function as your wish.

<html>
<head>
</head>
<body>
<img src="bulboff.jpg" height=200 width=200 id="imm" align="right">

<script type="text/javascript">

function bulb() {

var b = document.getElementById("imm");

if(b.src.match("bulboff.jpg")) {
 b.src = "bulbon.jpg";
}
 else {

 b.src="bulboff.jpg";
}
}
 setInterval(bulb,100);
</script>
</body>
</html>

Upvotes: 1

Guilherme Cunha
Guilherme Cunha

Reputation: 3

Try this!

function changeimage() {
    var image = document.getElementById('imagem');
    if (image.src.match("img")) {
        for(i = 1; i <= 3; i++) {
            image.src = "img/image2"+i+".png";
        }
    } else {
        image.src = "img/image1.png";
    }
}

Upvotes: 0

Rajashekhar
Rajashekhar

Reputation: 479

 <script type="text/javascript">
        function changeImage(a) {
    var picName=a.substring(1,a.length-1);
            document.getElementById("image").src=picName;
        }
 </script>

 <div id="main_img">
     <img id="image" src="app.jpg">
 </div>

 <div id="thumb_img">
     <img src='app.jpg'  onclick="changeImage('+5steps.jpg+');">
     <img src='5steps.jpg'  onclick="changeImage('+award.png+');">
     <img src='award.png'  onclick="changeImage('+app.jpg+');">
 </div>

Use the above code by placing this html file and pics(take care in namings, beacause I have given the above code with my pic names) in same folder you will get...

Upvotes: 0

Ronald Coarite
Ronald Coarite

Reputation: 4746

I also tube that problem. But solve it by an instance of an image every time you change the source (image).

It seems that would be called onload only once. But this way, you can change image whenever you want.

function chageIcon(domImg,srcImage)
    {
        var img = new Image();
        img.onload = function()
        {
            // Load completed
            domImg.src = this.src;
        };
        img.src = srcImage;
    }

Mode use.

chageIcon(document.getElementById("img"),"newIcon.png");

Upvotes: 5

user180100
user180100

Reputation:

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

demo here

Upvotes: 31

ShaneC
ShaneC

Reputation: 2406

You've got a few changes (this assumes you indeed still want to change the image with an ID of IMG, if not use Shadow Wizard's solution).

Remove a.src and replace with a:

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a;
}
</script>

Change your onclick attributes to include a string of the new image source instead of a literal:

onclick='changeImage( "1772031_29_b.jpg" );'

Upvotes: 3

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

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:

onclick='changeImage(this);'

Then in the function:

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

Upvotes: 16

Related Questions