I am currently using this code for several images:
<script>
$(function () {
$("img.cat").click(function() {
$(this).css('border', "solid 2px #ff0000");
});
});
</script>
The code works fine but I only want 1 image bordered at a time. So is there any way to modify the code so that it clears all borders or even add a white border so it’s not visible to add the images with class “cat” and then add the red border to the latest clicked image?
You can do this:
You just select all the images with the same class again and remove their borders, then continue with setting the border of the one that was just clicked.
Also, as long as you’re using jQuery 1.7 (you can use
delegate()for earlier versions), then it’s recommended that you useon()to attach event handlers. This would look like this:To make it more efficient, you could select the closest parent element that all the elements share. For example, if the images were all children of a
divwith the idimageContainer, you would do this: