cosmichero2025
cosmichero2025

Reputation: 1029

How to change an img src with javascript?

I know there are other questions like this and I've tried following them I'm just not aware of what exactly I'm doing wrong. I've declared the pic variable as being linked to the image with the corresponding id of 'pic' and I've tried many different examples and trying to follow other questions like this but to no avail.

--- THE REAL QUESTION ----

I would like the image to change its src to another one that I have in my workspace with the click of a button.

HTML:

<img class="trans" id="pic" src="images/link_rouge.png" alt="" width="1000" height="333" /> 

JavaScript:

var pic = document.getElementById('pic');

function rouge() {
    pic.src = "images/link_rouge.png";
}

function blue() {
    pic.src = "images/link_blue.png";
}

I know the functions already work with the buttons because they are affecting some divs on the page that change color the only things not changing are the images.

Upvotes: 3

Views: 40099

Answers (2)

Rayon
Rayon

Reputation: 36609

The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.

Use addEventListener over button elements to attach click events and bind your handler functions to those events.

var pic = document.getElementById('pic');

function rouge() {
  pic.src = "http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png";
}

function blue() {
  pic.src = "http://bin.smwcentral.net/u/1944/Link%2BBlue%2BTP%2Bshrunk.png";
}
document.getElementById('btn1').addEventListener('click', rouge);
document.getElementById('btn2').addEventListener('click', blue);
img {
  width: 200px;
}
<button id='btn1'>rouge</button>
<button id='btn2'>blue</button>
<br/>
<img class="trans" id="pic" src="http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png" alt="" width="1000" height="333" />

Upvotes: 7

Mike
Mike

Reputation: 11555

There's a chance your page has not loaded before pic is set equal to document.getElementById('pic');.

You can use something like jQuery's $(document).ready() function (or document.addEventListener("DOMContentLoaded", handler);) to ensure your page is fully loaded before assigning the pic variable.

$( document ).ready(function() {
    var pic = document.getElementById('pic');

    function rouge() {
        pic.src = "images/link_rouge.png";
    }

    function blue() {
        pic.src = "images/link_blue.png";
    } 
});

Note: You will need to pull the JQuery library into your project to use this method. See here.

Also, you can read this post to learn a little more about HTML/JavaScript and page loading.

Upvotes: 1

Related Questions