I am trying to change the big image when another small image is clicked, kind of like a product display on an e-commerce website. But my code doesn’t seem to work.
JavaScript
x
13
13
1
jQuery(document).ready(function($) {
2
$('.blue-button').on({
3
'click': function() {
4
$('#change-image').attr('src', 'https://cdn.shopify.com/s/files/1/0781/4423/files/02_8df18841-8d84-4a96-9611-e5a965dce73c.jpg?v=1568864598');
5
}
6
});
7
8
$('.yellow-button').on({
9
'click': function() {
10
$('#change-image').attr('src', 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/mothers-day-flower-bouquet-1588610191.jpg');
11
}
12
});
13
});
JavaScript
1
8
1
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<div class="button-container">
4
<img src="https://i.pinimg.com/originals/12/e2/6d/12e26d72c68442640b27583cff8d50e7.png" class="blue-button box">
5
<img src="https://i.pinimg.com/originals/16/cd/d9/16cdd95fab4a41e8cbe3e1f724343f49.png" class="yellow-button box">
6
</div>
7
8
<img id="change-image" src="https://img.freepik.com/free-vector/beautiful-watercolour-bouquet-flowers_52683-45189.jpg?size=626&ext=jpg" />
Advertisement
Answer
Don’t repeat JavsScript code. Instead delegate a click to every .button-container
‘s img
element:
JavaScript
1
6
1
jQuery(function($) {
2
const $image = $("#change-image");
3
$(".button-container").on("click", "img", function() {
4
$image.attr("src", this.src);
5
});
6
});
JavaScript
1
1
1
.button-container img {max-height: 60px;}
JavaScript
1
8
1
<div class="button-container">
2
<img src="https://i.pinimg.com/originals/12/e2/6d/12e26d72c68442640b27583cff8d50e7.png" class="blue-button box">
3
<img src="https://i.pinimg.com/originals/16/cd/d9/16cdd95fab4a41e8cbe3e1f724343f49.png" class="yellow-button box">
4
</div>
5
6
<img id="change-image" src="https://img.freepik.com/free-vector/beautiful-watercolour-bouquet-flowers_52683-45189.jpg?size=626&ext=jpg"/>
7
8
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another suggestion is not to load the fullsize images if you need thumbnails.
Store the Full-size image inside the data-*
attribute of the thumbnail image:
JavaScript
1
6
1
jQuery(function($) {
2
const $image = $("#change-image");
3
$(".button-container").on("click", "img", function() {
4
$image.attr("src", this.dataset.src);
5
});
6
});
JavaScript
1
1
1
.button-container img {max-height: 60px;}
JavaScript
1
8
1
<div class="button-container">
2
<img src="https://placehold.it/50x50/0bf" data-src="https://placehold.it/250x150/0bf">
3
<img src="https://placehold.it/50x50/f0b" data-src="https://placehold.it/250x150/f0b">
4
</div>
5
6
<img id="change-image" src="https://placehold.it/250x150/0bf"/>
7
8
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>