Swap Image via Button with JQuery


Description: 

jQuery replace an image on click. This is a method to swap numerous images in HTML by manipulating the images src attribute value from the click of another element such as a button.




Kind:

jQuery


HTML:

<<div class="button-container">
<button class="black-button"></button>
<button class="red-button"></button>
<button class="blue-button"></button>
<button class="yellow-button"></button>
</div>

<img id="change-image" src="/wp-content/uploads/2018/09/black.jpg" alt="Black Image" />


Javascript:

jQuery(document).ready(function($){

$('.black-button').on({
'click': function(){
$('#change-image').attr('src','/wp-content/uploads/2018/09/black.jpg');
}
});

$('.red-button').on({
'click': function(){
$('#change-image').attr('src','/wp-content/uploads/2018/09/red.jpg');
}
});

$('.blue-button').on({
'click': function(){
$('#change-image').attr('src','/wp-content/uploads/2018/09/blue.jpg');
}
});

$('.yellow-button').on({
'click': function(){
$('#change-image').attr('src','/wp-content/uploads/2018/09/yellow.jpg');
}
});
});


URL: