Skip to content

Instantly share code, notes, and snippets.

@aresnick
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aresnick/77e86983e92ea1fcfb01 to your computer and use it in GitHub Desktop.
Save aresnick/77e86983e92ea1fcfb01 to your computer and use it in GitHub Desktop.

A small example of using a mouse interaction to control the animation of an element

This is a small example of using pressing-and-holding on a div to shrink the div (which otherwise grows without bound).

Further doing

Modify the code so that:

  1. …the circle doesn't extend over the edge of the page as it grows
  2. …it uses CSS transforms to animate its growth/shrinkage rather than JavaScript
  3. …it shrinks in proportion to the frequency of your clicks

Further reading

<html>
<head>
<style>
#circle { /* Make ourselves a 100px circle */
width: 100px;
height: 100px;
border-radius: calc(100px/2);
background-color: purple;
}
</style>
</head>
<body>
<div id='circle'>
</div>
<script>
var circle = document.getElementById('circle'); // Grab our circle element
var growthFactor = 0.01; // Set up a global variable we'll use to grow the circle each time step
var pressing = false; // Set up a global variable we'll use to keep track of whether someone is pressing on the circle or
var growBy = function(element, growthFactor) { // Make a convenience function which will change the radius of of our circle by `growthFactor`
var style = window.getComputedStyle(element); // Grab the current style of our circle; you can read more about getComputedStyle at https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
element.style.width = parseFloat(style.width) * (1 + growthFactor) + 'px'; // scale our width
element.style.height = parseFloat(style.height) * (1 + growthFactor) + 'px'; // and our height
element.style.borderRadius = parseFloat(style.borderRadius) * (1 + growthFactor) + 'px'; // and our border-adius
};
window.addEventListener('load', function() {
setInterval(function() { // every 10ms
if (pressing) { // If we're pressing
growBy(circle, -1*growthFactor); // shrink our cicle
}
else { // otherwise
growBy(circle, growthFactor); // grow it
}
}, 10);
});
circle.addEventListener('mousedown', function() {
pressing = true;
});
circle.addEventListener('mouseup', function() {
pressing = false;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment