Spoiler alert: I'm author of Grains.js. If you missed my previous article on Grains.js, please check it out here. Now I want to show how to use g-class directive for switching classes dynamically based on state. If you're building interactive UIs with plain HTML and want smooth transitions, animations, or dynamic styling — without using a full JS framework — then you'll love how g-class directive works in Grains.js. Let’s dive into a real-world example. Note: It's best to utilize TailwindCSS to use ready-made styles via their classes. g-class directive has nothing to do with TailwindCSS, however. It only switches class names based on state. After that, you can use whatever you want. ✨ Animated Notification Example We’ll build a notification box with: Visibility toggle Error/success state styles Shake animation for emphasis You can try the live demo here. You can see updated list of examples at https://github.com/mk0y/grains.js/tree/main/examples. ✅ Setup Add Grains.js and TailwindCSS to your page: Remember, using cdn.tailwindcss.com is not for production environments. I'm using it only for presentational purposes - you should build your css file instead. Next, add a simple @keyframes animation for shake: @keyframes shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } } .shake { animation: shake 0.5s ease-in-out; }

Apr 6, 2025 - 11:58
 0

Spoiler alert: I'm author of Grains.js. If you missed my previous article on Grains.js, please check it out here.

Now I want to show how to use g-class directive for switching classes dynamically based on state. If you're building interactive UIs with plain HTML and want smooth transitions, animations, or dynamic styling — without using a full JS framework — then you'll love how g-class directive works in Grains.js.

Let’s dive into a real-world example.

Note: It's best to utilize TailwindCSS to use ready-made styles via their classes. g-class directive has nothing to do with TailwindCSS, however. It only switches class names based on state. After that, you can use whatever you want.

✨ Animated Notification Example

We’ll build a notification box with:

  • Visibility toggle
  • Error/success state styles
  • Shake animation for emphasis

You can try the live demo here.

You can see updated list of examples at https://github.com/mk0y/grains.js/tree/main/examples.

✅ Setup

Add Grains.js and TailwindCSS to your page:



Remember, using cdn.tailwindcss.com is not for production environments. I'm using it only for presentational purposes - you should build your css file instead.

Next, add a simple @keyframes animation for shake: