DEV Community

Filip Biterski
Filip Biterski

Posted on

6

UI components in pure Javascript

Javascript UI libraries and frameworks often come with large files and sometimes are an overkill for small to medium projects. That's why I'd like to show you a way of building UI components with pure (vanilla) javascript, so that you can at least consider avoiding large UI libraries, and increase site's download performance as a result.


Here's an interactive example. We'll design a card with some text and a button that changes card's background color. You can see the final version on JSFiddle.

Card component

We first create the HTML Element node and add a class to it; Then declare a function for changing the background color; And append child components, passing applyRandomColor to the button component.

Note: for older browser support, instead of append method, use appendChild for each child.

function Card() {
    const node = document.createElement('div');
    node.classList.add('card');

    function applyRandomColor() {
        node.style.background = '#' + Math.floor(Math.random()*16777215).toString(16);
    }

    node.append(
        CardContent(),
        CardButton({pressHandler: applyRandomColor})
        )

    return node
}

CardContent component

More of the same.

Note: older browsers don't support classList method, for wider support use node.setAttribute('class', 'card__content');

function CardContent() {
    const node = document.createElement('div');
    node.classList.add('card__content');
    node.textContent = 'Text text text text text text text text text text text text';

    return node
}

CardButton component

More of the same.

Note how components can accept arguments and how all the variables and functions are contained inside their respective functions, and don't pollute the global scope.

function CardButton({pressHandler}) {
    const node = document.createElement('div');
    node.textContent = 'Press me';
    node.classList.add('card__button');

    node.addEventListener('click', pressHandler);

    return node
}

Append the Card component

document.body.appendChild(Card())

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay