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 :-)
function changeImage(a)
so there is no such thing as a.src
=> just use a
.
demo here
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");
}
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.
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" );'