Posts | Comments | Email

Using jQuery to make a fade in button

Today we will be looking at using jQuery to make a button with two states, a normal state and a hover state. But instead of making it change immediately, we will be making a nice fade in effect using, you guessed it, jQuery’s fadeIn() function.

First up, lets have a look at our CSS:

.button{
position:relative;
width: 100px;
height: 100px;
}
.button_normal{
width: 100px;
height: 100px;
background-image:url(sprite.png);
position:absolute;
}

.button_hover{
width: 100px;
height: 100px;
background-image:url(sprite.png);
background-position:0px -100px;
position:absolute;
display: none;
}

We have three elements, the first is our button div (with the class .button). This is our wrapper div, and also the element on which the actions will take place (the element that when the mouse enters/leaves the actions take place)

The next we have our two button states. You will see they are positioned absolute. This is important to make them sit on top of each other. The second class also start display: none so it is invisible at first. You will also notice the second class (the hover) uses the same background image as the other, but with a background-position of -100px. This is a sprite image. It it a great way of doing things because it means the browser only has to load one image to show both buttons. This is what the sprite image looks like:

Sprite - obey your thirst

Sprite - obey your thirst

Now for our html:

<div class="button">
    <div class="button_normal"></div>
    <div class="button_hover"></div>   
</div>

Easy enough, our wrapper div contains our two button states. Now for the fun part, our jQuery:

$(document).ready(function(){
$('.button').mouseenter(function(){
$('.button_hover').fadeIn();
});

$('.button').mouseleave(function(){
$('.button_hover').fadeOut();
});

$('.button').click(function(){
alert('boom!');
});
});

So we have our jQuery ready block, and within it we have 3 functions. The first is for when the mouse enters the element with the class .’button’ – our element button_hover fades in using jQuery’s fadeIn()

The second is when the mouse leaves the element, and our hover element fades out. Simple!

The last function self destructs your browser, so don’t press the button. As always, here is the magical demo, and you can download here. May the force be with you.

Share

Comments are closed.