Capsule examples

This page shows the examples of capsule frontend library.

Mirroring example

The example of mirroring the input value to another dom.

JS

const { on } = component("mirroring");

on.input = ({ query }) => {
  query(".dest").textContent = query(".src").value;
};

HTML


    
    

Result


Mount hook example

When you assign a function to "on.__mount__", it's called when the component is mounted.

JS

const { on } = component("hello");

on.__mount__ = ({ el }) => {
  el.textContent = `Hello, I'm ${el.textContent}! 👋`;
};

HTML


    
    

Result


Pubsub example

capsule supports pubsub pattern with "pub" and "sub" methods.

JS

const EVENT = "my-event";

{
  const { on } = component("pub-element");

  on.click = ({ pub }) => {
    pub(EVENT, { hello: "clicked!" });
  };
}

{
  const { on, sub } = component("sub-element");

  sub(EVENT);

  on[EVENT] = ({ e, el }) => {
    el.textContent += " " + e.detail.hello;
  };
}

HTML


    

Result


Event delegation example

Capsule supports Event delegation pattern.

JS

const { on } = component("delegation-example");

on(".btn").click = ({ query }) => {
  query(".result").textContent += " .btn clicked!";
};
    

HTML


    

Result


Outside event example

When you're creating floating UI patterns such as tooltips or modal dialogs, you often need to handle the events "outside" of the target dom. Capsule supports this pattern with "on.outside[eventName]".

JS

const { on } = component("outside-example");

on.outside.click = ({ el }) => {
  el.textContent += " outside clicked!";
}

HTML


    

Result


Prevent default example

If you need to preventDefault or stopPropagation, you can access it via '.e' prop.

JS

const { on } = component("prevent-example");

on.click = ({ e }) => {
  e.preventDefault();
  alert("A link is clicked, but the page doesn't move to the target url because the default behavior is prevented ;)");
};

HTML


    

Result

More details about capsule library is available in the github repository.