How to animate div width and height on mouse hover using jQuery?



We can animate the width and height of a div on mouse hover using jQuery by applying the animate() method to the div on hover. We can specify the desired width and height values as well as the duration of the animation. Additionally, we can also add a callback function to perform additional actions after the animation is complete.

jQuery is a JavaScript library that makes it easy to add interactive elements to web pages. jQuery is designed to make it easy to add dynamic content to a web page, and to make it easy to write code that works across different browsers. jQuery also provides a number of features that make it easy to create responsive and mobile-friendly web applications.

Approach

There are a few different ways that you could approach animating div width and height on mouse hover using jQuery.

  • One approach would be to use the jQuery .hover() method, which allows you to specify two functions to be executed when the mouse enters and leaves an element. Within the function that is executed on mouseenter, you could use the jQuery .animate() method to animate the width and height of the div. Something like this −

$("#someDiv").hover(function() { $(this).animate({ width: "100px", height: "100px" }, "slow"); }, function() { $(this).animate({ width: "50px", height: "50px" }, "slow"); });

Example

<!DOCTYPE html>
<html>
<head>
   <title>Animate DIV</title>
</head>
   <body>
      <div id='animate' style="color:black; background:red">hello  world</div>
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      <script>    
         jQuery("#animate").hover(
            function(){
               jQuery(this).animate({width: "300px", height: "300px"});
            },
            function(){
               jQuery(this).animate({width: "100px", height: "100px"});
            }
         );   
      </script>
   </body>
</html>

Advertisements