JianYA JianYA - 3 months ago 31
Javascript Question

Jquery background slide down

I was wondering if it is possible to change make the div follow the size of its table cell? At the moment I can only display something above another div. This is what I have so far.

https://jsfiddle.net/amosangyongjian/mmqasf5t/54/

$(document).ready(function(){
$("td").hover(function(){
$(this).find(".expand").slideDown("slow");
},function(){
$(this).find(".expand").slideUp("slow");
});
});

Answer

jsFiddle example

td {
  width:100px;
  height:100px;
  position:relative; /* ADD THIS */
}
.expand {
  display:none;
  position:absolute;
  top:0; left:0; width:100%; height:100%; /* ADD */
  z-index:1;
  background:red;
  /*height:auto; width:100%;  REMOVE */
  overflow:hidden;
}

.static {
  position:absolute;
  z-index:0;
  background:yellow;
  text-align:center;
}

And here's a much cleaner solution with some minor changes in HTML, CSS, jQuery

jQuery(function( $ ) {

  $("td").hover(function() {
    $(this).find(".expand").stop().slideToggle("slow");
  });

});
td {
  width:100px;
  height:100px;
  position:relative;
}
.expand {
  display:none;
  position:absolute;
  top:0; left:0; width:100%; height:100%;
  background:red;
  overflow:hidden;
}
.static {
  position:absolute;
  background:yellow;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="tableclass">
  <tr>
    <td>
      <div class="static">Hello1</div>
      <div class="expand">Expanded</div>
    </td>
    <td>
      <div class="static">Hello2</div>
      <div class="expand">Expanded</div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="static">Hello3</div>
      <div class="expand">Expanded</div>
    </td>
    <td>
      <div class="static">Hello4</div>
      <div class="expand">Expanded</div>
    </td>
  </tr>
</table>

and here's another example that uses no JavaScript at all
but CSS3 transition from height:0; to height:100%;

td {
  width:100px;
  height:100px;
  position:relative;
}
.static {
  position:absolute;
  background:yellow;
  text-align:center;
}
.expand {
  position:absolute;
  overflow:hidden;
  top:0; left:0; width:100%; height:0;
  background:red;
  transition: 0.5s;
}
td:hover .expand{
  height:100%;
}
<table border="1" id="tableclass">
  <tr>
    <td>
      <div class="static">Hello1</div>
      <div class="expand">Expanded</div>
    </td>
    <td>
      <div class="static">Hello2</div>
      <div class="expand">Expanded</div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="static">Hello3</div>
      <div class="expand">Expanded</div>
    </td>
    <td>
      <div class="static">Hello4</div>
      <div class="expand">Expanded</div>
    </td>
  </tr>
</table>

Comments