halfacreyum halfacreyum - 4 months ago 10
jQuery Question

How to hide nested element when parents width is 0?

Im trying to hide a nested p tag when its parents width is 0. essentially I want the nested p tag to follow the parent as its width approaches 0, as well as when it expands. I'm sure its something simple, thanks for any help in advance.

Fiddle

HTML:

<div class="container">
<div class="floater1">
<p id="icon">X</p>
</div>
<div class="floater2">
<p>This is a test</p>
</div>
</div>
<button>click</button>


CSS:

.container {
width: 100%;
height: 35px;
border: 1px solid #000;
}
.floater1 {
float: left;
width: 0px;
height: inherit;
background: red;
text-align: center;
transition: width 200ms ease-in-out;
}
.show {
width: 30px;
}
.floater2 {
height: inherit;
background: yellow;
overflow: hidden;
padding-left: 15px;
}
p {
margin: 0;
line-height: 35px;
}


JS:

var trigger = $('button');
var deleteBtn = $('.floater1');
trigger.click(function(){
console.log("hello")
deleteBtn.toggleClass('show');
})

Answer

You have to set the overflow:hidden; property to ".floater1" class. So that the p tag will be hidden when the parent width is 0.

var trigger = $('button');
var deleteBtn = $('.floater1');
trigger.click(function(){
	console.log("hello")
	deleteBtn.toggleClass('show');
})
.container {
  width: 100%;
  height: 35px;
  border: 1px solid #000;
}
.floater1 {
  float: left;
  width: 0px;
  height: inherit;
  background: red;
  text-align: center;
  transition: width 200ms ease-in-out;
  overflow:hidden;
}
.show {
  width: 30px;
}
.floater2 {
  height: inherit;
  background: yellow;
  overflow: hidden;
  padding-left: 15px;
}
p {
  margin: 0;
  line-height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="floater1">
    <p>X</p>
  </div>
  <div class="floater2">
    <p>This is a test</p>
  </div>  
</div>
<button>click</button>

See the working fiddle here

https://jsfiddle.net/davidsekar/7uk9n0ev/