tropic
tropic

Reputation: 15

Javascript image src not changing

I'm trying to make an image that switches between two sources every two seconds but the image isn't changing

<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic').src;
setInterval(function(){
if(pic == 'banner1.jpg'){
pic = 'banner2.jpg';
console.log('change1');
}
else{
pic = 'banner1.jpg';
console.log('change2');
}
}, 2000);
</script> 

Upvotes: 0

Views: 55

Answers (2)

DCR
DCR

Reputation: 15665

<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic')
console.log(pic.src)
setInterval(function(){
if(pic.src == 'https://stacksnippets.net/banner1.jpg'){
pic.src = 'https://stacksnippets.net/banner2.jpg';
console.log('change1');
}
else{
pic.src = 'https://stacksnippets.net/banner1.jpg';
console.log('change2');
}
}, 2000);
</script> 

Upvotes: 1

Ele
Ele

Reputation: 33726

You're assigning a value to a variable rather than the attribute src.

You need to set the new value to the attribute src

To check for the current url, using this: img.src.indexOf('banner1.jpg')

var img = document.getElementById('bannerPic');
setInterval(function() {
  if (img.src.indexOf('banner1.jpg') !== -1) {
    img.src = 'banner2.jpg';
    console.log('change1');
  } else {
    img.src = 'banner1.jpg';
    console.log('change2');
  }
}, 2000);
<img id="bannerPic" src="banner1.jpg">

Upvotes: 5

Related Questions