Webpage with four color images I have a very simple webpage that contains 4 color images. When I hover over any of the images the original (xxxx1.jpg) is replaced by a black and white version (xxxxx2.jpg) of the same image, and then it reverts back to the original image after hover.

I'm declaring the same variable for both handlerIn and handlerOut:

var src = $(this).attr("src")


Can I declare the var just once somehow? I just can't seem to figure this out myself.

$(document).ready(function(){
    $( "img" ).hover(
        function() {
            var src = $(this).attr("src").replace("1.jpg", "2.jpg");
            $(this).attr("src", src);
        }, 
        function() {
            var src = $(this).attr("src").replace("2.jpg", "1.jpg");
            $(this).attr("src", src);
        }
    );
});
The first thing I would do to make the code shorter is to take advantage of the fact that many jQuery methods like .attr() accept a function as the second argument, allowing you to replace this:

var src = $(this).attr("src").replace("1.jpg", "2.jpg");
$(this).attr("src", src);


...with this:

$(this).attr("src", function(i, v) { return v.replace("1.jpg", "2.jpg"); });


(and similar in the other function.) What this does is call the function in the second argument with the current value of the attribute as the v argument, so you don't need a separate call to .attr() to find out what the current value is, and you don't need the src variable.

Then I'd change the .hover() code to pass a single function to run on mouseenter and mouseleave, and use the event object to check whether it is mouseenter or mouseleave:

$(document).ready(function(){
  $("img").hover(function(e) {
    $(this).attr("src", function(i, v) {
      return v.replace(/[12]\.jpg/, (e.type === "mouseenter" ? "2" : "1") + ".jpg");
    });
  });
});


This uses a regular expression /[12]\.jpg/ with .replace() to find a string ending with "1.jpg" or "2.jpg", and replace it with a value depending on the event.type.

Demo: https://jsfiddle.net/g5ncjjxo/