How to animate the opacity of an element on mouse hover using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery animate() method

The CSS display inline-block is very useful for controlling the dimensions as well as margin and padding of the inline elements. However, while using the inline-block visual formatting the whitespace in the HTML code creates some visual space on the screen. But you can get rid of it using the following simple techniques.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <title>jQuery Animate Opacity on Hover</title>
  • <style type="text/css">
  •     ul{
  •         padding: 0;
  •         list-style: none;
  •     }
  •     ul li {
  •         float: left;        
  •         margin: 10px; 
  •     }
  •     ul li a img{
  •         opacity: 0.3;
  •     }
  • </style>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $("a").mouseenter(function(){
  •             $(this).find("img").finish().animate({
  •                 opacity: "1"
  •             });
  •         }).mouseleave(function(){
  •             $(this).find("img").finish().animate({
  •                 opacity: "0.3"
  •             });
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <ul>
  •         <li><a href="#"><img src="club.jpg" alt="Club Card"></a></li>
  •         <li><a href="#"><img src="diamond.jpg" alt="Diamond Card"></a></li>
  •         <li><a href="#"><img src="spade.jpg" alt="Spade Card"></a></li>
  •         <li><a href="#"><img src="heart.jpg" alt="Heart Card"></a></li>
  •     </ul>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.