CSS Font-Size and Units of Length

units-percentage

The number of devices accessing the same data and the same page grows fast. Creating a modern web page that makes every device view the same content in a simplified and adjusted way can be a challenge.

In this post we are gonna see the font-size property and the units of length, which will help you to understand and to create a responsive web page.

How many units of length does exist?

There are a lot of units of length and they can be separated as relative length and absolute length.

Relative length: relative to another length property. Units: em, ex, ch, rem, vw, vh, vmin, vmax and %.

Absolute length: fixed and will appear as exactly that size. Units: cm, mm, in, px, pt and pc.

Main units

The main and more used units of length are: px, em and %.

PIXELS (PX): have a fixed size and don’t change. Ems are relative to the font size set in the CSS. If you are accessing on a screen with higher resolution, the fonts will be rendered smaller. It’s good and bad at the same time, just depends on what you need.

EM: don’t have a fixed size and can change. One good thing is that they are scalable, in other words, good for mobile web development. One “bad” or complicated thing is that they cascade, making the perfect pixel more difficult. For example: 1.2em of 16px = ~19.2px

PERCENT (%): don’t have a fixed size and can change. Very similar to EM unit, however using percentage. For example: 1.5em = 150%

Conclusion

These three kind of units are good to use in font-size property. You just need to adjust and to select the best for your project. Relative lengths can be a good choice for web development and for a responsive design. If you have never used other unit but pixels, try to use percentage, they are very good and it’s popularity is growing.

What is a WebHook?

webhook

A few days ago I needed to consume a webhook and it caused some confusions in my mind. Now it’s clear for me but at that time, I couldn’t understand what exacly it was, how it worked and the difference between a webservice and a webhook.

And that’s why I am here now writting this post (:

Definition

Webhooks are “user-defined HTTP callbacks”. They are usually triggered by some event, such as pushing code to a repository or a comment being posted to a blog. When that event occurs, the source site makes an HTTP request to the URI configured for the webhook. Users can configure them to cause events on one site to invoke behaviour on another. The action taken may be anything. https://en.wikipedia.org/wiki/Webhook

Webhook vs webservice

It’s like an inverted API endpoint. Instead of making a call for any API, you define a callback URL to which the service that provide the webhook will send an HTTP POST for your API. That’s the difference between the webhook and webservice.

Consuming a Webhook

The first thing you need to do is to set up a URL to your webhook provider. Generally, you can do it through a control panel or an API. Basically, that’s all . After a registered URL, the events will be sent to you. So now, you need to be prepared to receive them!

Below we can see a list of events and their flow. According to these events you can start creating your API.

SENDGRID-WEBHOOK-3

SENDGRID-WEBHOOK-2

https://sendgrid.com/docs/API_Reference/Webhooks/event.html

Data sent

When and what kind of data will the provider send me?

It depends on your provider. Probably there is a documentation listing the events and the kind of data you need to expect. Most of webhooks will POST data to you in one of two ways: as JSON or XML to be interpreted, or as a form data (application/x-www-form-urlencoded or multipart/form-data).

Example of data:

SENDGRID-WEBHOOK-5

https://sendgrid.com/docs/API_Reference/Webhooks/event.html

Conclusion

Webhooks are excellent and provide us a better real time integration. It’s growing and most of the big companies already have it. Sure, you can create a webhook and not just consume them. This post was just an introduction but there are other important things, for example how to debug it and security things. You can find these kind of things easily (:

Why to write a good code?

font-end-vs-back-end

A few weeks ago, I came across this image above and because of that I’ve decided to write this post, showing the importance of writing a good code.

What does “a good code” mean?

I think the variables may change slightly depending on the language we are using, but there are some general rules that apply to all languages.

There are some points:

  • When you have to add or modify a feature, is it too difficult?
  • Do you constantly break existing functionality when making changes?
  • Is it hard to understand some code that you are seeing for the first time?

If you’ve answered “yes”, you need to start reviewing your code.

Why to write a “good code”?

Doesn’t matter if we are talking about client side or server side. The consequences of writing a bad code can be terrible for the developer himself.

What is my code doing?
This question seems to be crazy, but I am sure that you have already asked yourself.

It is just a text field, should be easier to implement
Yes, sometimes an easy thing can become a problem or take a long time to implement.

I just modified that and nothing else works.
Functions and code blocks should be well defined and isolated, so you would not destroy the whole system when editing a single line.

How to write a “good code”?

  1. Plan Before You Write
  2. Commenting & Documentation
  3. Good Indentation
  4. Avoid Deep Nesting
  5. Consistent Variable Names
  6. Code Refactoring

If you do not know some concept above, please just google it. I’ve listed a few important ones, but there are a lot more.

Conclusion

Try to challenge yourself in writing a better code. Ask for help from a more experienced developer on how you could improve your code. And the most important, before writing the code, think about the best way to do it, even if it takes a few precious minutes, I’m sure it will be worth it.

ES6: Template strings

template strings

Quick post about template strings. If you are learning Ecmascript 6, you should read this post. This is the new way to embed variables in texts.

About

Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings

Template strings are enclosed by the back-tick (` `). So if you don’t have been using the back-tick, you should find it now on your keyboard, it will be very used from now.

To embed a variable in a text, you need to indicate it by the Dollar sign and curly braces (${expression}).

Examples

Syntax

'use strict';

let age = 23;

console.log('I am ' + age + ' years old.'); // normal strings

console.log(`I am ${age} years old.`); // template strings

Multi-line strings

'use strict';

// normal strings

console.log("my text line 1\n" + 
"my text line 2\n" + 
"my text line 3\n" + 
"my text line 4\n");

// template strings

console.log(`my text line 1
my text line 2
my text line 3
my text line 4`);

Expressions

'use strict';

let a = 13;
let b = 10;

// normal strings

console.log("I am " + (a + b) + " years old and not " + (2 * a + b) + ".");

// template strings

console.log(`I am ${a + b} years old and not ${2 * a + b}.`);

Conclusion

Template strings are already being used and will be used more and more. So if you’re not used to it, get used to!
For you who is studying Ecmascript 6, take a look: https://github.com/airbnb/javascript (Airbnb JavaScript Style Guide)

Javascript Hoisting

hoisting

In the previous post, I wrote about strict mode in Javascript and how it is beneficial and helps you to write a better code. For example, to do not forget to declare a variable.

But, did you know that in Javascript you can declare a variable after accessing it?

Hoisting

In JavaScript, functions and variables are hoisted. Hoisting is JavaScript’s behavior of moving declarations to the top of a scope (the global scope or the current function scope). https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Examples

Variable

'use strict';

x = 'Declaring a variable after using it.'; // It works!
document.write(x);

var x;

Function

myFunction(10); // It works!

function myFunction(x) {
    console.log(x);
}

Cool. You’ve just seen that you can declare variables and functions after accessing them.

Ecmascript 6

Everybody is talking about Ecmascript 6, right? What about changing the example above from var to let and also make an example with class? It should work, right? Let’s see!

let

'use strict';

x = 'Declaring a variable after using it.'; // ReferenceError
document.write(x);

let x;

As you can see, let does not hoist the variable to the top of the block. You need to declare before using it.

class

var a = new myClass(1, 2); // ReferenceError

class myClass {
    constructor(x, y){
        this.x = x;
        this.y = y;
    }
}

Class declarations are not hoisted too. You first need to declare and then access it, otherwise code will throw a ReferenceError.

Conclusion

Hoisting is an unknown or overlooked behavior of JavaScript (to many developers). All you need to do to avoid bugs is always declare all variables at the beginning of every scope. Of course, always using the javascript strict mode. If you didn’t see my post about strict mode, check it out: http://blog.guinatal.com/javascript-use-strict/

JavaScript Use Strict

strict-mode

If you’re starting to encode javascript or you are already a javascript programmer and have never seen the strict mode before, check out this post.

About strict mode

I always recommend coding javascript in strict mode. Strict mode makes changes to normal javascript semantics. An important aspect is that the strict mode eliminates silent errors, forcing you to write a better code and don’t make mistakes.

Invoking strict mode

To invoke the strict mode, you just need to write ‘use strict'; in your javascript file, for example.

'use strict';

Now that you already know how to invoke strict mode, let’s see a quick example.

Quick example

'use strict';
foo = 'Guilherme'; // ReferenceError

You need to declare the variable.

'use strict';
var foo = 'Guilherme'; // It works!

Now it works!

Conclusion

As you can see, strict mode can help you a lot to write a better javascript code. If you wanna see more examples and know more how it exactly works, take a look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Working with currency in Javascript

currency_vs_javascript

These days I was developing in VB.NET. This application was working basically as a web service, and through the Javascript I made my asynchronous requests.

Everything was working fine, but I was working with currency. If you’ve already worked with currency, probably you should have had some problem. Especially if your backend project is set to a different culture type.

I am Brazilian, usually the projects that I work are configured as pt-BR. The response that I got from the web service was a currency setted to pt-BR. Examples: R$ 10,00 / R$ 1.000,00

Of course, I could just change the culture type of the web service return, it would make my life easier, but I hadn’t this option. I had to do everything in Javascript and I didn’t want to import a currency library.

Come aboard!

Currency to float

The first thing I needed to do is to create a function that would transform currency in a float.

function real2float(moeda) {
    moeda = String(moeda);
    moeda = moeda.replace("R$", "");
    moeda = moeda.replace(/\./g, ""); // it replaces all dots
    moeda = moeda.replace(",", ".");
    return parseFloat(moeda);
}
real2float("R$ 1.000,00") // 1000
real2float("R$ 974.430,30") // 974430.30
real2float("R$ 1.966.854,88") // 1966854.88

Now I could work with these numbers and make calculations. After that, I needed to transform these numbers in currency again to display them on screen.

Float to currency

To transform float to currency, I used the method toLocaleString.

“The toLocaleString() method returns a string with a language sensitive representation of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.”

function float2real(valor) {
    valor = parseFloat(valor).toFixed(2).toString();
    valor = parseFloat(valor).toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
        minimumFractionDigits: 2
    });
    valor = valor.replace("R$", "R$ ");
    return valor;
}
float2real(100.00) // R$ 100,00
float2real(500.29) // R$ 500,29
float2real(504440.93) // R$ 504.440,93

Conclusion

If you do work with a several types of currency in Javascript, could be a good idea to use some library. GitHub exists to help you to find good libraries and frameworks.
Or if you work with just one type of currency, I would recommend you to create manually 2 simple functions, like I did.
To know more about the toLocaleString method, take a look at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

CSS Fade In Animation

fadeIn

Have you already used a css animation in your project? They can make your website looks much more refreshed and modern visually. Today we’re gonna create the fadeIn effect.

Let’s assume the following code:

In the code above, if you click on the Result tab, you will see that the page loads at once, without any effect. We want to create an effect that when the page is loaded, the element loads in a fade effect.

@keyframes and animation

First of all, we need to create our @keyframes from opacity 0 to 1.

@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

Great, now we can create a class called fade-in and invoke our effect named fadeIn.

.fade-in {
  opacity: 0; // invisible from the start
  animation: fadeIn ease-in 1; // call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time
  animation-fill-mode: forwards; // this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)
  animation-duration: 1s;
  animation-delay: 0.3s; // delay to start
}

Now, you just need to put the class fade-in in the element that you want to create the effect. If you want to create this effect for all your content, you can apply it on the body tag.

To see the final result, click on the Result tab below. You could also take a look on the CSS tab, I added some codes for better compatibility.

Conclusion

These effects are very simple to implement and make your website looks modern and even in some cases faster. If you want to learn more about CSS animation, I would recommend https://developer.mozilla.org/en-US/docs/Web/CSS/animation

Javascript: querySelector vs getElementById

getElementById

I’ve realized that most of people usually don’t use the querySelector, thus I decided to write quick examples and the basic differences between querySelector and selectElementById as well as querySelectorAll and getElementsByClassName.

http://www.w3.org/TR/selectors-api/

Selectors, which are widely used in CSS, are patterns that match against elements in a tree structure. The Selectors API specification defines methods for retrieving Element nodes from the DOM by matching against a group of selectors. It is often desirable to perform DOM operations on a specific set of elements in a document. These methods simplify the process of acquiring specific elements, especially compared with the more verbose techniques defined and used in the past.

querySelector vs selectElementById

Let’s assume the following code:

<form id="userForm">
  <input id="username" type="text" value="Guilherme" />
</form>

We want to get the username element and allocate it in a variable. First let’s do this using getElementById.

var username = document.getElementById("username");

Now, let’s get the same element but this time using querySelector.

var username = document.querySelector("#userForm #username");

As you can see, using the querySelector the element that we want to select is much more specific and defined. The result is exactly the same.

getElementById image 1

querySelectorAll vs selectElementByClassName

Let’s assume the following code:

<form id="productForm">
  <input id="productOne" class="product" type="text" value="Product 1" />
  <input id="productTwo" class="product" type="text" value="Product 2" />
  <input id="productThree" class="product" type="text" value="Product 3" />
</form>

We want to get all the products elements and allocate them in a variable. First let’s do this using getElementByClassName.

var products = document.getElementsByClassName("product");

Now, let’s get the same elements but this time using querySelectorAll.

var products = document.querySelectorAll("#productForm .product");

The result is almost the same, but the getElementsByClassName returns a HTMLCollection and the querySelectorAll returns a NodeList.

getElementById image 2

Great! But these examples are very simple, so let’s try something a bit more difficult.

<table id="tableProducts">
  <thead>
    <tr>
      <th>Product</th>
      <th>Value</th>
    </tr>
   </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>100</td>
    </tr>
    <tr>
      <td>B</td>
      <td>200</td>
    </tr>
    <tr>
      <td>C</td>
      <td>300</td>
    </tr>
  </tbody>
</table>

In the example above, we have a table of products and we need to sum the values. I guess that there are some ways to do it, but let’s use querySelectorAll.

var sum = 0;
var cells = document.querySelectorAll("#tableProducts>tbody>tr>td:nth-of-type(2)");

for (var i = 0; i < cells.length; i++)
  sum += parseFloat(cells[i].firstChild.data);

Very simple, isn’t it?

Conclusion

The querySelector and querySelectorAll are really very powerful and work well when you need to select more specific elements. They are supported by most of current browsers. If you wish, here you can check the supported browsers: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Browser_Compatibility

Getting Started with Sass

sass-logo

Today I am going to talk about Sass and SCSS but there are others preprocessors available. For example: LESS.

Sass is a preprocessor that is interpreted into CSS. In practice it means you will write codes in Sass language and it will be converted into CSS. It helps you reduce repetition with your CSS.

Sass vs SCSS

Differences between Sass and SCSS. http://sass-lang.com/documentation/

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.

Getting Started

I considered writing about how to install the Sass but everything you need you can find here: http://sass-lang.com/install

Finally, let’s write some code!

The first thing you need to know is that Sass allows you to use variables. It keeps your code much more organized.

SASS SYNTAX

$font-stack: Helvetica, sans-serif
$primary-color: #333
$font-small: 15px
$font-medium: 30px
$font-large: 60px
$blue: #186DEE
$grey: #E5E5E5

SCSS SYNTAX

$font-stack: Helvetica, sans-serif;
$primary-color: #333;
$font-small: 15px;
$font-medium: 30px;
$font-large: 60px;
$blue: #186DEE;
$grey: #E5E5E5;

The second thing you need to know is that with Sass your code will be much more organized visually as well. Sass and SCSS are written in a visual hierarchy.

SASS SINTAX

.content
  padding: 20px
  background-color: $grey
  +border-radius(5px)

  &:hover
    background-color: $blue

  span
    display: block

  span.one
    font-size: $font-small

  span.two
    font-size: $font-medium

  span.three
    font-size: $font-large

SCSS SINTAX

.content {
  padding: 20px;
  background-color: $grey;
  @include border-radius(5px);

  &:hover {
    background-color: $blue;
  }

  span {
    display: block;
  }

  span.one {
    font-size: $font-small;
  }

  span.two {
    font-size: $font-medium;
  }

  span.three {
    font-size: $font-large;
  }
}

Note: in the code below we are using a mixin. But to use it, we need to create it. Otherwise our code will not compile.

Mixins

A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. http://sass-lang.com/guide

SASS SINTAX

=border-radius($radius)
  -webkit-border-radius: $radius
  -moz-border-radius: $radius
  -ms-border-radius: $radius
  border-radius: $radius

SCSS SINTAX

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  -ms-border-radius: $radius;
  border-radius: $radius;
}

Conclusion

Writing codes in Sass or SCSS is really very simple and even if you have never seen them before, but you have a good knowledge of CSS, you will able to assimilate, understand and write codes.

If you want to practise and improve your skills, there are some online compilers and you can use them for free. Take a look at http://sassmeister.com/

There’s another good service if you don’t want to write your own mixins: here you can find a simple and lightweight mixin library for Sass. http://bourbon.io/