The main problem here is your anchor element, which cause the page to reload
Simply remove the anchor element and give the image a pointer cursor
Without anchor a, with cursor on image
$('img').on({
'click': function() {
document.querySelector('span').textContent = $(this).attr('src');
var src = ($(this).attr('src') === 'animals/5/')
? 'animals/6/'
: 'animals/5/';
$(this).attr('src', src);
}
});
#img1 {
cursor: pointer;
}
span {
vertical-align: top;
padding: 5px 10px;
background: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<base href="http://lorempixel.com/300/300/">
<img id="img1" src="animals/5/" height="300" width="300">
<span></span>
With anchor a, which will not work properly
$('img').on({
'click': function() {
document.querySelector('span').textContent = $(this).attr('src');
var src = ($(this).attr('src') === 'animals/5/')
? 'animals/6/'
: 'animals/5/';
$(this).attr('src', src);
}
});
span {
vertical-align: top;
padding: 5px 10px;
background: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<base href="http://lorempixel.com/300/300/">
<a href="#"><img id="img1" src="animals/5/" height="300" width="300"></a>
<span></span>
Another option is to cancel the event bubbling, and keep the anchor a, though I still recommend to simply remove it
$('img').on({
'click': function(e) {
document.querySelector('span').textContent = $(this).attr('src');
var src = ($(this).attr('src') === 'animals/5/')
? 'animals/6/'
: 'animals/5/';
$(this).attr('src', src);
e.stopPropagation();
return false;
}
});
span {
vertical-align: top;
padding: 5px 10px;
background: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<base href="http://lorempixel.com/300/300/">
<a href="#"><img id="img1" src="animals/5/" height="300" width="300"></a>
<span></span>