K A
K A

Reputation: 125

How do I set up a jQuery animation for my on-hover function?

So basically I have some code that makes it so when a user hovers over a certain image it changes that image to another image. Basically I want to add a jQuery animation or transition between these 2 events so that the image fills up vertically. Here is the code I have so far:

<script type="text/javascript">
  function hover(element) {
    element.setAttribute('src', 'assets/banner-focus.png');
  }

  function unhover(element) {
    element.setAttribute('src', 'assets/banner.png');
  }
</script>
<img src="assets/banner.png" onmouseover="hover(this);" onmouseout="unhover(this);">

Upvotes: 0

Views: 58

Answers (1)

Haolin
Haolin

Reputation: 171

Add an event listener to the image.

<img src="assets/banner.png" id="image">
$( document ).ready( function() {
    $( "#image" ).hover(
      function() {
        $( this ).attr("src", "assets/banner-focus.png").animate({height: "20px"}, 500);
      }, function() {
        $( this ).attr("src", "assets/banner.png" ).animate({height: "500px"}, 500);
      }
    );
});

JSFiddle: https://jsfiddle.net/y1s7d28j/4

Upvotes: 1

Related Questions