Image Swap on Click
Click on the image to swap between the next image and then the original image.
HTML
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
<h2>Image Swap on Click</h2>
<p>Click on the image to swap between the next image and then the original image.</p>
<div class="d-flex justify-content-between align-items-start flex-wrap iswap">
<img class="img-fluid" src="http://saj.bss.design/assets/img/desk.jpg?h=9943d0aaec924a3b7027809a369f32f6" data-iswap="building.jpg" data-oswap="desk.jpg">
<img class="img-fluid" src="http://saj.bss.design/assets/img/building.jpg?h=caffb1c1581c5da2fb703dc76803cf86" data-iswap="loft.jpg" data-oswap="building.jpg">
<img class="img-fluid" src="http://saj.bss.design/assets/img/loft.jpg?h=7089baf3aed19c1ebfdb3b22b910ec17" data-iswap="desk.jpg" data-oswap="loft.jpg">
</div>
</div>
CSS
@media (min-width:768px) {
.iswap img {
max-width: 32%
}
}
JavaScript
$("[data-iswap]").on("click", function() {
var $this = $(this);
var $iSRC = $this.attr("src");
var $newSRC = $this.data("iswap");
var $oldSRC = $this.data("oswap");
var $newImgSrc = $iSRC.replace(/\w+\.(?![com|net|org|biz|info|live|me|design])\w+/g, $newSRC);
var $oldImgSrc = $iSRC.replace(/\w+\.(?![com|net|org|biz|info|live|me|design])\w+/g, $oldSRC);
if ($newImgSrc.indexOf($iSRC) === -1) {
$this.attr("src", $newImgSrc);
} else {
$this.attr("src", $oldImgSrc);
}
});