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())
Top comments (0)