Skip to content

Instantly share code, notes, and snippets.

@encody
Created July 6, 2016 12:43
Show Gist options
  • Select an option

  • Save encody/4e2ef59ea41c216ca2f110ea7180ac38 to your computer and use it in GitHub Desktop.

Select an option

Save encody/4e2ef59ea41c216ca2f110ea7180ac38 to your computer and use it in GitHub Desktop.
Button Ripple Effect
/*
Video Guide: https://youtu.be/QI2rDHQM5Pc
*/
body {
background-color: #333;
}
button {
font-family: "Roboto";
font-size: 24px;
padding: 1em 2em;
margin: 3px;
border: 0;
outline: 0;
color: white;
background-color: #2196F3;
text-transform: uppercase;
border-radius: 0.15em;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
overflow: hidden;
position: relative;
/*
Not discussed in tutorial; this ensures that the ripple
circle doesn't go over the border-radius of the button
*/
z-index: 1;
}
button .ripple {
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
position: absolute;
transform: scale(0);
animation: ripple 0.6s linear;
}
@keyframes ripple {
to {
transform: scale(2.5);
opacity: 0;
}
}
/*
Video Guide: https://youtu.be/QI2rDHQM5Pc
Note: You may want to wrap this code in a self-executing
anonymous function to prevent globals from being created:
(function () {
...
})();
*/
var buttons = document.getElementsByTagName('button');
Array.prototype.forEach.call(buttons, function (b) {
b.addEventListener('click', createRipple);
});
function createRipple (e) {
/*
Note that these next two lines will create a
NEW ripple element for each click. If this is
undesirable behavior, try:
* Setting a timeout to delete the element
* Checking if an element has already been made & reuse it
* Create an element around line 8 and always reuse it
* etc.
*/
var circle = document.createElement('div');
this.appendChild(circle);
var d = Math.max(this.clientWidth, this.clientHeight);
circle.style.width = circle.style.height = d + 'px';
circle.style.left = e.clientX - this.offsetLeft - d / 2 + 'px';
circle.style.top = e.clientY - this.offsetTop - d / 2 + 'px';
circle.classList.add('ripple');
}
<!--
Video Guide: https://youtu.be/QI2rDHQM5Pc
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Button Ripple</title>
<link rel="stylesheet" href="button.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<button>
Click Me!
</button>
<button>
Click Me!
</button>
<button>
Click Me!
</button>
<script src="button.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment