Search code examples
javascriptjqueryjquery-animatewidth

How to resize multiple divs at the same time smoothly when hover over each one using jquery


What I want to do is

increase the width of the div that gets hovered over and equally decrease the width of the other 3 divs.

So if "div1" get hovered over, then "div1" width needs to be "40%"

and

the other 3 divs widths would go to "20%" which would equal 100%

This works with the code I have, but its not smooth and when I hover fast over multiple divs everything goes haywire. It's very buggy

What am I doing wrong?

Link of what I'm trying to do: https://constructlar.atakansaracoglu.com/

My HTML:

<div class="container">
   <div class="div1">
   </div><div class="div2">
   </div><div class="div3">
   </div><div class="div4">
   </div>
</div>

My CSS:

.container div {
   position: relative;
   display: inline-block;
   width: 25%;
}

My Script:

$(document).ready(function(){
  $('.container div').hover(function(){
     let $this = $(this);
     $this.siblings().animate({
       'width' : '19%'
     },200);
     $this.delay(200).animate({
       'width' :'40%'
     },300);
  });
});

Solution

  • Using CSS and transition property instead of jQuery makes the page smoother.

    .container div {
       position: relative;
       display: inline-block;
       width: 25%;
       height: 100px;
       transition: width 0.4s;
    }
    
    .container:hover div {
        width: 20%;
    }
    
    .container div:hover {
        width: 40%;
    }
    <div class="container">
       <div class="div1" style="background:red">
       </div><div class="div2" style="background:cyan">
       </div><div class="div3" style="background:yellow">
       </div><div class="div4" style="background:green">
       </div>
    </div>