Here's the same thing done in few different ways. They all do the same thing, with varying degrees of compactness.
The last one is probably most convenient and the most flexible one. You never have to touch your javascript to change the image src
values.
http://jsfiddle.net/yPAqY/
Html:
<img id="imageid" src="imagegray.png" alt="">
jQuery:
$(document).ready(function () {
$('#imageid').on("click", function () {
var obj = $(this),
objAttr = obj.attr('src'),
first_img = 'imagegray.png',
second_img = 'imagecolor.png';
if (objAttr === first_img) {
obj.attr('src', second_img);
} else if (objAttr === second_img) {
obj.attr('src', first_img);
}
});
});
http://jsfiddle.net/yPAqY/1
Html:
<img id="imageid" src="imagegray.png" alt="">
jQuery:
$(document).ready(function() {
$('#imageid').on("click", function() {
var obj = $(this),
first_img = 'imagegray.png',
second_img = 'imagecolor.png',
imgs = obj.attr('src') == first_img ? second_img : first_img;
obj.attr('src', imgs);
});
});
http://jsfiddle.net/yPAqY/2/
Html:
<img id="imageid" src="imagegray.png" data-img2="imagecolor.png" alt="">
jQuery:
$(document).ready(function() {
var image = $('#imageid'),
imageSrc = image.attr('src'),
imageData = image.data('img2');
image
.removeAttr('data-img2')
.on("click", function() {
var obj = $(this),
imgs = obj.attr('src') == imageSrc ? imageData : imageSrc;
obj.attr('src', imgs);
});
});