Skip to content
Manolo Edge edited this page Oct 28, 2023 · 10 revisions

What are Tags?

The core concept for Cardboard is the Tag, internally represented by the class CTag. It's designed so you don't need to use this class directly. But you might need to add it as a type if you write with TS, so it's good to know it exists.

Creating tags

To create a CTag you can use the tag function

tag('div', tag('p', 'Hello!'));

While you can use the tag function directly, normally you will use the built-in tag function and not the tag function directly:

import { allTags } from 'cardboard-js';
const { div, p } = allTags;
div(p('Hello!'));

allTags contains all the known HTML elements.

Adding tags

A tag represents an element in the page. They can be a new element, or a wrapper over existing elements in the page. When you create a tag, it will not be added to the DOM unless you manually add them. This can be done in a few ways.

  • Adding as a child:
div(
  p('Hello!')
);
  • Adding with append or prepend
div().append(
  p('Hello!')
);
div().prepend(
  p('Hello!')
);
  • Attaching to attached tags. By calling .attach, the element will be added as a child of div.
    Read more about Attaching.
attach(div());

p.attach('Hello!');
p.attach('Hello!');

You can modify anything from a tag as you would with HTML or JS, and a bit more. You can modify the text, if the element is present in the DOM or not, you can add styles, set attributes, add events, etc... You can also modify tags based on some states.

div("Some text")
  .addStyle('color', 'green')
  .disabled()
  .addAttr('tooltip', 'hey!!')

Take a look at Manipulating Tags for a more in-depth explanation.

Cardboard offers a few different ways of managing text.

const st = state({ count: 0 });
div("Count: ", st.count);
div().text("Count: $count", st);
div(text("Count: $count", st));

Take a look at Managing Text for a more in-depth explanation.

Events

Tags provide a flexible event-handling mechanism to manage interactions and respond to user actions. You can add event listeners to tag for a wide range of events, such as click, keypress, change, and more.

// Example 1: Adding a click event listener
const button = tag('button');
button.clicked((tag, evt) => {
  console.log('Button clicked!');
});

// Example 2: Adding a keypress event listener for the Enter key
const input = tag('input');
input.keyPressed((tag, evt) => {
  if (evt.key === 'Enter') {
    console.log('Enter key pressed!');
  }
});

Take a look at the Event Handling guide for more in-depth documentation.

➡️ Next: Attaching.
➡️ Next: State.
➡️ Next: Reusable Components.