Image swap with jQuery

a basic jQuery example

by Mindy McAdams

HTML

<h1>Swap an image on hover</h1>

<div id="foobar">
    
<img src="http://macloo.com/images/african_animals/zebra.png" alt="An animal icon">
   
</div>

CSS

body {
    font-family: Calibri, sans-serif;
}

div {
    background: #99ff66;
    padding: 10px;
}

JavaScript

// using jQuery 

var lion = "http://macloo.com/images/african_animals/lion.png";
var zebra = "http://macloo.com/images/african_animals/zebra.png";


$('#foobar').on('mouseenter mouseleave', function() {
    if ( $('#foobar img').attr('src') == lion ) {
        $('#foobar img').attr('src', zebra);
    } else {
        $('#foobar img').attr('src', lion);
    }
});

// note that "#foobar" refers to the div with that id, and when we
// write '#foobar img' - ANY image inside that div will be affected