Sunday, November 29, 2015

Using JQuery to play a GIF on hovering the mouse over.

I used JQuery to implement the hover functionality.

The objective is to play a GIF image when the mouse is on the image and image should go static when the mouse is out of image area.

Once the mouse is out of the image area, the image goes static.

HTML + JQuery code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head>
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
 </head>
 <body>
  <img src="image_1_static.jpg" id="id1"/>
  <script>
   $(document).ready(function() {
    $("#id1").hover(
     function() {
      $(this).attr("src", "image_1.gif")
     }, function() {
      $(this).attr("src", "image_1_static.jpg")
     }
    );
   });
  </script>
 </body>
</html>


For achieving the above, I took a GIF (image_1.gif), opened the GIF in mspaint and saved it as jpeg/jpg image (image_1_static.jpg), now I have a static image and a GIF.

I took src for the img as the static image (image_1_static.jpg) and in the hover, I have written two functions one that accepts gif (image_1.gif) when mouse hovers over the img area and one that accepts jpeg/jpg (image_1_static.jpg) when mouse is out of img area.

This functionality can be very useful for creating menu icons in a website. When user places mouse over, icon plays.

Suggestions are well appreciated and happy learning.

No comments:

Comments

blog comments powered by Disqus