I want to make a button that simply change photo src from given src of image
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="Avatar" >
</div>
I have new1.JPG to new6.JPG photo which should be changed on this image source on click of a button All photos are in my /img/ folder And here is my HTML code for the button to change src with onclick.
<button id="changeimg" > Change </button>
CodePudding user response:
As @Teemu said (in comments), if you have the list of the new images you want to change to, you can do it by js code.
<div id="main_photo">
<img class="card-img-top" id="mainImage" src="/img/new0.JPG" alt="Avatar" >
</div>
<button id="changeimg" onclick="changeImage()"> Change </button>
<script>
var imageIndex = 0;
var imageCount = 6; // Can be also an array of images names ["/img/new0.JPG", "/img/new1.JPG", ..., "/img/new6.JPG"]
function changeImage() {
var imageContainer = window.getElementById("mainImage");
imageContainer.src = "/img/new" (imageIndex ) ".JPG";
// Make sure you validate the counter so it won't overflow
}
</script>
CodePudding user response:
I have a demo for you if you have the list of images. And I believe that you can have that by simple code to get all images in your local folder.
const listSources = [
'/img/new0.JPG',
'/img/new1.JPG',
'/img/new2.JPG',
'/img/new3.JPG',
'/img/new4.JPG',
'/img/new5.JPG',
'/img/new6.JPG',
]
var currentIndex = 0;
$('#changeimg').click(function() {
// increase index to show the next image
currentIndex ;
// reset if reach the last image
if (currentIndex == listSources.length) currentIndex = 0;
// set image src
$('#main_photo>img').first()
.attr('src', listSources[currentIndex])
.attr('alt', listSources[currentIndex]); // change alt to show changes in demo
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeimg">Change</button>
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="/img/new0.JPG">
</div>