Skip to content

Instantly share code, notes, and snippets.

@lk-snippets
Created April 2, 2012 19:14
Show Gist options
  • Save lk-snippets/2286472 to your computer and use it in GitHub Desktop.
Save lk-snippets/2286472 to your computer and use it in GitHub Desktop.
Changing an image on hover
<!-- First include the jQuery library. You can just include Google's hosted version of jQuery by including the below script. -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<!-- Then comes our code. -->
<script type="text/javascript">
$(function(){ //Don't worry about this part
$('#image-to-switch').hover( //Finds the HTML element in the same way as CSS... this grabs the image with the id of "image-to-switch", then we call the magic hover function
function(){ //The hover function contains two other functions. The first defines what you want to do when the mouse enters the object
$(this).attr('src', 'some-new-image.jpg'); //$(this) refers to the element you selected previously (#image-to-switch). Then we ask to change the attribute (attr) named 'source' (src) to some new value (some-new-image.jpg)
},
function(){ //...The second function defines what you want to do when the mouse leaves the object
$(this).attr('src', 'the-old-image.jpg'); //We'll want to change the img source back to the original image once the mouse leaves
});
}); //Don't worry about this part
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment