Created
November 17, 2023 22:51
-
-
Save santiagoaloi/fc6253f9c4962a877b472b227438b6aa to your computer and use it in GitHub Desktop.
shake directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/directives/shakeDirective.js | |
export const shakeDirective = { | |
install(app) { | |
// Create the styles dynamically | |
const styleTag = document.createElement('style') | |
styleTag.innerHTML = ` | |
.shake { | |
animation: shake 1s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; | |
transform: translate3d(0, 0, 0); | |
backface-visibility: hidden; | |
perspective: 1000px; | |
} | |
@keyframes shake { | |
10%, 90% { | |
transform: translate3d(-1px, 0, 0); | |
} | |
20%, 80% { | |
transform: translate3d(2px, 0, 0); | |
} | |
30%, 50%, 70% { | |
transform: translate3d(-4px, 0, 0); | |
} | |
40%, 60% { | |
transform: translate3d(4px, 0, 0); | |
} | |
} | |
` | |
// Append the styles to the document head | |
document.head.appendChild(styleTag) | |
// Now, install the directive | |
app.directive('shake', { | |
beforeMount(el, binding) { | |
// Set up the initial state based on the initial value | |
updateClasses(el, binding.value) | |
}, | |
updated(el, binding) { | |
// Check if the value has changed and update the classes accordingly | |
if (binding.value !== binding.oldValue) { | |
updateClasses(el, binding.value) | |
} | |
} | |
}) | |
} | |
} | |
function updateClasses(el, isShaking) { | |
el.classList.toggle('shake', isShaking) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment