JavaScript is disabled! Please enable JavaScript in your web browser!

Freestyle Academy of Communication Arts & Technology

1299 Bryant Ave, Mt. View, CA 94040 T 650-940-4680   F 650-961-1346
2 Required Classes: English and Design 3rd/Elective Class:  + Animation or Digital Media or Film
Freestyle Logo

Font Size




Back to list of all examples

Useful Stuff About:

Button Hovers and Clicks

Problem: How do you have both jquery hover and click animations work in sync and logically?

This is an example of of soliving the problem with these features:

Hover/Click on a button below to see demo


Scripts needed (copy and paste inside <head>)

<script src=""></script>

Here's the html code

<div class="btn" id="btn1">
<a href="#" target="_blank"><img id="imgbtn1" src="path/to/image1.png"/></a>
<div class="btn" id="btn2">
<a href="#" target="_blank"><img id="imgbtn2" src="path/to/image2.png"/></a>
<div class="btn" id="btn3">
<a href="#" target="_blank"><img id="imgbtn3" src="oath/to/image3.png"/></a>

Here's the CSS

.btn {
background-position:0 -50px;//change this to half the height of the image sprite
overflow:hidden;//hides the top half of the image sprite
#btn1 {
background-image: url(path/to/image1.png);
#btn1 {
background-image: url(path/to/image2.png);
#btn1 {
background-image: url(path/to/image3.png);

Here's the javascript code

var imgClicked, imgHovered, fadeTime=500;
imgClicked = "#"+ $("#btn1").find("img").attr("id");
$(".btn").hover(function () { //actions to occur when you hover ON
imgHovered = "#" + $(this).find("img").attr("id")//IMPORTANT!!!
if (imgHovered!=imgClicked){//if the hovered image is NOT the same as the clicked image
$(imgHovered).stop().animate({"opacity":"0"},fadeTime,"linear");//Animate the hovered image to fade out
}, function () { //actions to occur when you hover OFF
if (imgHovered!=imgClicked){//if the button image hovered is NOT the same as the clicked image
$(imgHovered).stop().animate({"opacity":"1"},fadeTime,"linear");//Animate the hovered image to fade in
$(".btn").click(function () {
if (imgHovered!=imgClicked){//if the button hovered on is NOT the same as the currently clicked button
$(".btn").find("img").css({//Resets all buttons to have default hand pointer
"cursor": "pointer"
$(imgClicked).stop().animate({"opacity":"1"},fadeTime,"linear");//fades IN previously clicked button
imgClicked = "#" + $(this).find("img").attr("id");//Stores new value for currently clicked button image
$(imgClicked).css({"opacity":"0"});//Sets the currently clicked image to transparent
$(imgClicked).css({//Changes current button image to NOT have the hand pointer
"cursor": "default"
btnClicked=$(this).attr("ID");//Stores new value for currently clicked button ID for use in other functions
//actions for clicked button