DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Avichay Eyal
Avichay Eyal

Posted on

Custom Directives in slim.js

I will demonstrate how to apply a visual effect (typewriter as an example) using custom directives in slim.js.

For those aren't familiar with slim.js - It is a web-component authoring library with zero dependencies, fast, lightweight (3K) that enables developers to create custom elements with the declarative approach (similar to how Angular handles templates).

Demo of the effect here

First, lets define some component with a basic template:

Slim.tag('my-tag',
`<p effect:typewriter>This is a sample text</p>`
class extends Slim {
});

If you have noticed the effect:typewriter attribute, it is still not defined as a custom directive, and will have no effect on the page.
Attributes with namespaces a VALID html markup and they can be leveraged in order to avoid conflicts with native future attributes.

Now let's define the effect directive

Slim.customDirective(
    (attribute) => attribute.localName === 'effect:typewriter',
    (source, target, attribute, match) => {
        // capture initial text
        const text = target.innerText;
        // parse delay from attribute or default to 50ms
        let delay = parseInt(attribute.nodeValue || '50');
        let i = 0;
        const interval = setInterval(() => {
          target.innerText = text.slice(0, i++); // set inner text
          if (i > text.length) {
            clearInterval(interval);
          }
        }, delay);
    }
);

In the HTML Markup we can now add

<my-tag></my-tag>

And viola, typewriter effect anywhere we want.

For more information regarding slim.js you can see the online docs here

Oldest comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await