Sunday, January 17, 2021

Css Animations

CSS Animations

If you're looking to add an extra zest to your already perfect webpage, why not add some animations?

It could be in the form of smooth transitions and waverings to convey a natural consequence of the users action, rather than cold magic.

So, how do we animate HTML elements?

We just need to add 2 sections of code into your CSS.

First, on the element we want to animate, we'll need to specify the ammount of time it will animate, and the name of the animation.

animation-duration: 2s;
animation-name: rainbowWave;

Second, we'll need to add a new "at-rule" (@keyframes) with the information how the element should look at different times of the animation.
In this example, as soon as the element is rendered the element will start with a red background, then will gradually become green for the next second, and finally transition to blue.

@keyframes rainbowWave {
    from {
        background-color: red;
    }
    50% {
        background-color: green;
    }
    to {
        background-color: blue;
    }
}

At the end of the animations the styles will jump back to the ones specified outside the animation. 

Just a word of caution, while small animations can give a nice feel to your website, too much animation can distract the user too much, make the website look childish and can put a big burden on the rendering engine.

Monday, January 4, 2021

Bind elements

Ever needed to set the text of an element asynchronously?

Sometimes we want to use data that is dynamic or is stored outside our file or project.

In those cases, when we get the data, we can bind it with our elements.

Here's a simple example:

HTML:

<p data-test="p1">Placeholder 1</p>
<p data-test="p2">Placeholder 2</p>
<p data-test="p3">Placeholder 3</p>

JS:

var mockedAsyncData = {
     p1: "Hello",
     p2: "World",
     p3: "!!!!!"
}
var targetElements = document.querySelectorAll("[data-test]");

targetElements.forEach( element => {
    var attrValue = element.getAttribute("data-test");

     element.innerHTML =
mockedAsyncData[attrValue];
});
 

In this example, we set up 3 p elements with placeholders, and when the JS runs, it populate the p elements with the values from the data object.

Using vanilla JS works well, but if you'd like to put less code you can use a famous library: the KnockOutJs. 

It does exactly what's above (and much more) with less lines of code.

HTML:

<p data-bind="text: p1">Placeholder 1</p>
<p data-bind="text: p2">Placeholder 2</p>
<p data-bind="text: p3">Placeholder 3</p>

JS:

var viewModel= { 
    p1: "Hello",
    p2: "World",
    p3: "!!!!!"
};

ko.applyBindings(viewModel);

And that's it. The only thing to remember is to use data-bind="text: ..., and to use ko.appyBlindings() with the data. 


KnockoutJs is also able to iterate through arrays (like displaying a list from a template), read values and much more.