Animated Add/Remove items

by Yaroslav Samardak

HTML

<button onclick="appendEl()">Add</button>
<div id="container"></div>

SCSS

* {
  box-sizing: border-box;
	outline: none;
	user-select: none;
}

button {
	background-color: #43A047;
	border: none;
	color: white;
	display: block;
	padding: .4em 2em;
	width: 100%;
	text-align: center;
	text-decoration: none;
	display: inline-block;
	font-size: 1em;
	transition: background .218s ease-in-out;
	cursor: pointer;
	
	&:hover {
		background-color: #2E7D32;
	}
}

#container {
	margin-top: 1em;
}

.note-wrapper {
  display: block;
  overflow: hidden;
  height: auto;
  max-height: 7em;
  opacity: 1;
  width: 100%;
  transition: max-height .218s linear, opacity .218s .218s ease-in-out;
	
	> .note {
		background: rgba(33, 33, 33, .2);
		margin-bottom: 1em;
		height: 5em;
		cursor: pointer;
		transition: background .436s ease-in-out;
		
		&:hover {
			background: rgba(33, 33, 33, .4);
			transition: background .218s ease-in-out;
		}
	}
	
	&.hidden {
		max-height: 0em;
		opacity: 0;
		transition: max-height .218s .218s linear, opacity .218s ease-in-out;
	}
}

JavaScript

var container = document.getElementById('container');

window.removeEl = function(el) {
  el.className = 'note-wrapper hidden';
  setTimeout(function() {
    container.removeChild(el);
  }, 500);
}

window.appendEl = function() {
  var div = document.createElement('div');
  div.className = 'note-wrapper hidden';
  div.onclick = function() {
    removeEl(div);
  };

  var note = document.createElement('div');
  note.className = 'note';
  div.appendChild(note);

  if (container.firstElementChild) {
    container.insertBefore(div, container.firstElementChild);
  } else {
    container.appendChild(div);
  }

  setTimeout(function() {
    div.className = 'note-wrapper';
  }, 1);
}