DEV Community

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:

`<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

    (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) {
        }, delay);

In the HTML Markup we can now add


And viola, typewriter effect anywhere we want.

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

Top comments (0)