Morphing Icons with CSS Web Animations (or "hamburger-x-morph")

2015-02-17 00:00:00 by Mike

Click the navigation icon below to start the animation.

Here is the HTML

<div id="navigation-container" data-component="navigation">
	<div id="icon-container">
		<div class="nav-icon top"></div>
		<div class="nav-icon middle"></div>
		<div class="nav-icon bottom"></div>
	</div>
</div>

Here is the CSS

#navigation-container {
	cursor:pointer;
}

#icon-container {
	cursor:pointer;
	padding:5px;
	display:inline-block;
	margin:4em auto 0 auto;
	position:relative;
}

#icon-container div.nav-icon {
	width:20px;
	height:3px;
	background:#000;
	cursor: pointer;
	position:absolute;
}

#icon-container div.nav-icon.top {
	top:0;
}

#icon-container div.nav-icon.middle {
	top:6px;
}

#icon-container div.nav-icon.bottom {
	top:12px;
}

/* animation styles */

#icon-container div.nav-icon.top.close {
	-webkit-animation-duration: .25s;
  animation-duration: .25s;
  -webkit-animation-name: morphTop;
  animation-name: morphTop;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

#icon-container div.nav-icon.middle.close {
	-webkit-animation-duration: .25s;
  animation-duration: .25s;
  -webkit-animation-name: morphMiddle;
  animation-name: morphMiddle;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

#icon-container div.nav-icon.bottom.close {
	-webkit-animation-duration: .25s;
  animation-duration: .25s;
  -webkit-animation-name: morphBottom;
  animation-name: morphBottom;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@keyframes morphTop {
  from {
    top:0;
    transform: rotate(0deg);
  }
  to {
    top:6px;
    transform: rotate(-45deg);
  }
}

@-webkit-keyframes morphTop {
  from {
    top:0;
    transform: rotate(0deg);
  }
  to {
    top:6px;
    transform: rotate(-45deg);
  }
}

@keyframes morphMiddle {
  from {
    opacity:1;
  }
  to {
    opacity:0;
  }
}
@-webkit-keyframes morphMiddle {
  from {
    opacity:1;
  }
  to {
    opacity:0;
  }
}

@keyframes morphBottom {
  from {
    top:12px;
    transform: rotate(0deg);
  }
  to {
    top:6px;
    transform: rotate(45deg);
  }
}
@-webkit-keyframes morphBottom {
  from {
    top:12px;
    transform: rotate(0deg);
  }
  to {
    top:6px;
    transform: rotate(45deg);
  }
}

Lastly, here is the JavaScript

var poz = {
	navigation: function() {
		var container = document.getElementById("navigation-container");
		var iconLines = document.getElementsByClassName("nav-icon");
		container.addEventListener("click", function() {
			for (var a=0; a < iconLines.length; a++) {
				iconLines[a].classList.add("close");
			}
			container.classList.add("open");
		});	
	},
	init: function() {
		poz.navigation();
	}
}

window.addEventListener("load", function() {
	poz.init();
})