I have this code that basically swaps an image every time the related checkbox is clicked. However, the jQuery code seems quite repetitive and I'd be interested to know how I could write this to be cleaner.
$(function() {
$('#switch1').change(function(){
if ($(this).is(':checked')) {
$('#image1').attr('src','image1-swap-png');
} else {
$('#image1').attr('src','image1-swap-png');
};
});
$('#switch2').change(function(){
if ($(this).is(':checked')) {
$('#image2').attr('src','image2-swap-png');
} else {
$('#image2').attr('src','image2-swap-png');
};
});
$('#switch3').change(function(){
if ($(this).is(':checked')) {
$('#image3').attr('src','image3-swap-png');
} else {
$('#image3').attr('src','image3-swap-png');
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>First example</h3>
<div>
<input type="checkbox" id="switch1">
<label>Checkbox</label>
</div>
<img id="image1" src="image1.png">
<h3>Second example</h3>
<div>
<input type="checkbox" id="switch2">
<label>Checkbox</label>
</div>
<img id="image2" src="image2.png">
<h3>Third example</h3>
<div>
<input type="checkbox" id="switch3">
<label>Checkbox</label>
</div>
<img id="image3" src="image3.png">
Thanks in advance