Instantly share code, notes, and snippets.

@nutbread /transitions.html Secret
Last active Aug 29, 2015

Embed
What would you like to do?
CSS transition stopping
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Transitions</title>
<style>
#test1,#test2 {
width: 100px;
height: 100px;
background: red;
transform-origin: 0 0;
transition: transform 1s linear 0s;
}
#test2 {
background: blue;
}
#test2.modified {
transform: scale(2,1);
}
</style>
</head>
<body>
<div id="test1"></div>
<div id="test2"></div>
<button id="b1">transition</button>
<button id="b2">stop</button>
<button id="b3">immediate</button>
<button id="b4">immediate &amp; start</button>
<script>
var test1 = document.querySelector("#test1");
var test2 = document.querySelector("#test2");
var toggle_transition = function (n, use_style) {
n.classList.toggle("modified");
if (!use_style) return;
if (n.classList.contains("modified")) {
n.style.transform = "scale(2,1)";
}
else {
n.style.transform = "";
}
};
var stop_transition = function (n) {
//n.style.display = "none"; // These 3 lines are commented as it still seems to work in all modern browsers this way
n.style.transition = "none";
window.getComputedStyle(n).getPropertyValue("transform");
n.style.transition = "";
//n.style.display = "";
//window.getComputedStyle(n).getPropertyValue("display");
};
document.querySelector("#b1").addEventListener("click", function () {
toggle_transition(test1, true);
toggle_transition(test2, false);
}, false);
document.querySelector("#b2").addEventListener("click", function () {
stop_transition(test1);
stop_transition(test2);
}, false);
document.querySelector("#b3").addEventListener("click", function () {
toggle_transition(test1, true);
toggle_transition(test2, false);
stop_transition(test1);
stop_transition(test2);
}, false);
document.querySelector("#b4").addEventListener("click", function () {
toggle_transition(test1, true);
toggle_transition(test2, false);
stop_transition(test1);
stop_transition(test2);
toggle_transition(test1, true);
toggle_transition(test2, false);
}, false);
var on_transitionend = function (event) {
// This is not fired when stop_transition is called
console.log("Transition of " + event.propertyName + " ended in " + event.elapsedTime + "s (event=" + event.type + ")");
};
test1.addEventListener("transitionend", on_transitionend, false);
test1.addEventListener("webkitTransitionEnd", on_transitionend, false);
test1.addEventListener("oTransitionEnd", on_transitionend, false);
test1.addEventListener("otransitionend", on_transitionend, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment