Home > other >  Expanding div on hover relative to a parent div with jQuery
Expanding div on hover relative to a parent div with jQuery

Time:02-03

I have a parent div with a few children:

<div id="main">
   <div id="child1">
      <div id="child2">
         <div id="child3">content</div>
      </div>
   </div>
</div>

The CSS is:

#main {width: 700px;}
#child1 {width: 150px;}
#child2 {width: 100%;}
#child3 {width: 100%;}

On hover, I want #child3 to expand to 90% width of #main, not be constrained to the 150px of its parent.

I tried giving #child3 a fixed width in px, but that caused a lot of issues with content spilling outside the #main div. I want to keep the expanded content of #child3 inside #main at all times.

Can this be done with JavaScript or jQuery? Please advise. Thanks!

JSFiddle here.

CodePudding user response:

Consider the following.

$(function() {
  $("#child3").hover(function() {
    // In
    $(this).css("width", $("#main").width() * 0.9);
  }, function() {
    // Out
    $(this).css("width", "");
  });
});
#main {
  width: 700px;
  box-shadow: inset 0 0 0 1px #000;
  padding: 10px;
}

#child1 {
  width: 150px;
}

#child2 {
  width: 100%;
}

#child3 {
  width: 100%;
  box-shadow: inset 0 0 0 1px #c00;
  padding: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
  <div id="child1">
    <div id="child2">
      <div id="child3">content</div>
    </div>
  </div>
</div>

Using .hover(), .css(), .width() you can calculate a new width that is 90% the width of another element. You can assign this and then re-assign it after.

See More:

  •  Tags:  
  • Related