Home > OS >  Can I use event listener and document.getElementById to change the src of an image?
Can I use event listener and document.getElementById to change the src of an image?

Time:05-24

JAVASCRIPT code is:

img1Click = document.querySelector('img#img1')

selected = document.querySelector('section.selected')
img = document.querySelector('img#imgcon')

img1Click.addEventListener('click', () =>{
    console.log('clicked')
   document.getElementById('imgcon').src('images/yellowcake.jpg')
})

This code is supposed to make change the src of a img of a div when another image is clicked.

CodePudding user response:

You nearly had it, although src isn't a function!

You can set it by doing image.src = ... or image.setAttribute('src', '...')

Here is a simplified example:

const image = document.querySelector("img");

image.addEventListener("click", () => {
  image.setAttribute("src", "https://picsum.photos/id/2/200/200")
})
<img src="https://picsum.photos/id/1/200/200" alt="">

CodePudding user response:

Yes, you can program

document.getElementById('id_of_element').src = 'image'

Where image is a base64 string or a file path in your directory (x.png).

CodePudding user response:

const imgA = document.querySelector('#imgA');
const imgB = document.querySelector('#imgB');

imgA.addEventListener('click', () => imgB.src = imgA.src);
imgB.addEventListener('click', () => imgA.src = imgB.src);
<div>
  <img id='imgA' src="https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=64"/>
  
  <img id='imgB' src="https://lh3.googleusercontent.com/-ugd4YTD60WY/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclfd8tK4TmHmCGTFZSkqc8VSPTITA/s96-c/photo.jpg?sz=64"/>
</div>

CodePudding user response:

You can do it with syntax: document.getElementById('imgcon').src = "images/yellowcake.jpg"

img1Click = document.querySelector('img#img1')

selected = document.querySelector('section.selected')
img = document.querySelector('img#imgcon')

img1Click.addEventListener('click', () =>{
    console.log('clicked')
   document.getElementById('imgcon').src = 'https://www.thespruceeats.com/thmb/y9Sj9blj6uM14YUdM6FlZv2dhEI=/2667x2000/smart/filters:no_upscale()/piece-of-yellow-cake-with-vanilla-frosting-186880544-57eade013df78c690fe89768.jpg'
})
img {
 width: 400px;
 height: auto;
}
<img id="img1" src="https://douongcaocap.vn/wp-content/uploads/2015/08/click-here-button.png" >
<img id="imgcon" src="https://www.recipetineats.com/wp-content/uploads/2018/03/Chocolate-Cake_9-SQ.jpg">

  • Related