Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Select tags by attribute in CSS

It is possible in CSS to select tags just based on the value of an attribute. Take for example for following HTML:

<input type="email" placeholder="Your email" />
<input type="password" placeholder="Your password" />
<input type="password" placeholder="Confirm password" />

If you want to select just the inputs that are of type passwod we will just need the following code:

input[type="password"] {
    background-color: yellow; }
}

This is the attribute selector in CSS.

But what if we want to target just the links that have an URL attached to them:

<a href="google.com">Search</a>
<a onclick="alert('hi')">Show alert</a>
<a href="js-craft.io">Learn CSS</a>

Here we don't have a constant index-value pair like in the first example, but we can say:

a[href] { 
    background-color: yellow; 
}

And wait there is even more we can do:

  • [test~="foo"] : Checks if the value of the attribute test contains the word foo no matter of the position.
  • [test|="foo"] : Checks if the value of the attribute test starts with the word foo.
  • [test^="foo"] : Checks if the value of the attribute test has the first 3 letters foo.
  • [test$="foo"] : Checks if the value of the attribute test ends with the word foo.

How I’ve started to learn programming

My initial plan was to be a math teacher or a doctor like my parents. I've become a software developer by chance ... and because of a broken computer.

When I was 10 my father bought me an Amiga computer. The kind that you would have to connect to your TV as it did not have a monitor.

At the beginning of the 90's this was considered a hi-tech device 😀

But that computer was broken and could not be connected to a cassette player. This meant that I could not load and play any games on it. Cuz, yes during those times a game was stored on a cassette tape.

The only thing I could do with that that computer was to run the BASIC programming language on it.

However, I've managed to get my hands on a book with a title like "How to make 10 games in BASIC".

I was typing about 3-4 pages of code to get a basic game up. A very complex game. Something like a red dot chasing two other blue dots.

I had no idea what I was doing. Lucky the BASIC programing language is made of short lines, so it was quite easy to track down a typo. Mostly I was copying the code like a monkey.

Another downside of not being able to connect this computer to a cassette player was that I did not have any way to save that code. When the computer was unplugged I was losing all of my code and had start from scratch again.

The funny thing was that after you write that code for enough number of times, those stage lines start to have some logic. I've started to change the color codes, the pixel values and see what was happening. Trial and error.

I was feeling like a wizard learning spells.

This did not get any practical application until highschool when I've discovered that I can skip a lot of the boring classes by taking part in some scholar computer contests.

And from there realized I could make this into a job and so on ...

So, a few takeaways from the story:

  • programming can be thought at a very young age. I was 10 year when started how to code, and for sure I don't have any special IQ.
  • video games are good; if it was not for the need to play those video games, maybe I would not be a programmer today. For sure I would not be interested in learning how to code if the aim was to solve a math equation.
  • it's ok, in the beginning to just copy. I think that the human brain, especially the brain of children, is super good in recognizing and learning patterns and adapt.

Cheers and happy learning!

Using Ellipsis to truncate long text lines in CSS

I use grammarly.com to correct the articles from this blog given that English's not my primary language. In this app, if you set a longer title a document you will get the ellipsis sign after a specific length.

This can be done quite easily in CSS thanks to the declaration text-overflow: ellipsis;.

Hoever keep in mind that for this to work you will also need to:

  • set a clear width to the text so that there is a limit for how much the text can expand
  • and also a nowrap alongside overflow: hidden so that the text will stay on one line and will not go outside the container

The full declaration for a truncation class may look like this:

.truncate-to-300 { 
    text-overflow: ellipsis; 
    width: 300px;
    white-space: nowrap; 
    overflow: hidden; 
}

And to get the output from the picture we can just to:

<h1 class="truncate-to-300">A CSS tricky situation- the order of the CSS class names in the HTML tags</h1>

There are also techniques that allow to truncate the text after multiple lines but there are a bit more troublesome to implement.

How to use Counters in CSS

We know that in HTML there we have the ol - ordered lists. By default what they do is to add a counter in front of any element that is on the list.

For example, the below is an ordered list made with ol and li tags:

  1. Cats
  2. Lions
  3. Tigers
  4. Jaguars

Those numbers are added by using CSS Counters. And we can add this behavior to any element we want, not just ordered lists.

Take for example the following HTML code:

<section>
    <h4>The Cats</h4>
    It is the only domesticated species in the family.
</section>
<section>
    <h4>The Lions</h4>
    It is a muscular, deep-chested cat with a short, rounded head.
</section>
<section>
    <h4>The Jaguars</h4>
    This spotted cat closely resembles the leopard, but is usually larger and sturdier.
</section>

If we want to add numbers to all h4 of a section first we will need to set the name and the value to zero for a new counter:

body { counter-reset: sectionsCounter; }

Next for each section we see, we will want to increment the counter:

section {counter-increment: sectionsCounter;}

And finally, use the counter’s value as content for the :before of a h4:

h4: before { content: counter(sectionsCounter) ". "; }

And voila. Now we’ll have section headings like 1. The Cats and 2. The Lions and so on.

See the full example here.

Throttling VS Debouncing in Javascript

A few days ago I've written a short article about debouncing in Javascript.

Another term very related to debouncing is throttling. Both techniques do the same thing: they make sure expensive operations (like API calls) are limited in a time interval.

But, in different ways:

  • throttling makes sure that one function is not called more than once in X milliseconds
  • meanwhile debouncing makes sure that a function is executed only if it was not called again for the past X milliseconds; basically with debouncing we make sure a function is called only once, even if it was involved multiple times.

A simple implementation for a throttling function may look like this:

function throttle(f, t) {
    return function (args) {
         let previousCall = this.lastCall;
        this.lastCall = Date.now();
            if (previousCall === undefined || (this.lastCall - previousCall) > t) { 
                f(args);
            }
     }
}

You can see in the other tutorial the implementation for the debouncing function.

For example, if we have a user is pressing a button every 500 milliseconds for 6 seconds:

  • with a throttling interval of 2 seconds, the call for the button will take place 3 times.
  • with a debouncing time of 500 milliseconds, then after 6 seconds, the call for the button only takes place just once

Also if you want to read more I have found useful the following links:

How to use the currentColor value in CSS

In CSS we have a special color value named currentColor that maybe be unknown to most people.

What currentColor does is to take the value for the color property and use it for any other property there has a color parameter.

For example the following:

.red-box {
    color: red;
    border: 2px solid red;
    box-shadow: 5px 10px red;
}

Is the same as having:

.red-box {
    color: red;
    border: 2px solid currentColor;
    box-shadow: 5px 10px currentColor;
}

It provides us with increased flexibility for our CSS. We just have to change the color in one place. Think of it as a CSS variable for colors only.

And it works even with inherited values too. For example:

body {
    color: blue;
}
p {
    border: 1px solid currentColor;
    // will create paragraphs with a blue border
}

Hoever, keep in mind that the rules of cascading apply also here. If we have an inherited value and we set a new color for the child, that new value will have priority.

And it works even with inherited values too. For example:

body {
    color: blue;
}
p {
    border: 1px solid currentColor;
    color: red;
    // will create paragraphs with a RED border
}

What is debouncing in Javascript

On the UI some user actions are expensive.

For example, a search operation can be expensive if we do it for every keypress. If the user types a word with 6 characters, and we search at every keyup event then we will have 6 API calls in a very short interval.

The fix would be to make the actual search only after the user had finished typing the search term. In other words, make the API call one second later after no key was pressed anymore for one second.

And this is were debouncing comes into play.

Debouncing makes sure that a function is not called again until a certain amount of time has passed without it being called.

For example, if the user is typing javascript we should search just for the jull word and not for:

  • j
  • ja
  • jav ...

Here is how one simple implementation of a debouncing function may look like:

function debounce(callback, time) {
    let interval;
    return () => {
        clearTimeout(interval)
        interval = setTimeout(() => {
                interval = null
                callback(arguments)
            }, time)
    }
}

Besides searching debouncing can be used with other expensive operations such as resizing a window, scrolling or autocomplete a text input based on an API call.

You can find here the full working example.

The double negation !! in Javascript

While working on a bug I have stumbled upon the following piece of code.

return !!(this.isFirstOverall() || this.get('videoId'));

I was super sure it is a mistake, and that was the root of the bug. It did not make any sense to negate a negation.

But after a bit of googleing I have found that there is such a thing as dobule negation in Javascript.

Long story short, its purpose is to convert any expression to an actual true/false boolean value.It is like having Boolean( insert_value_here.).

Take for example the follwoing expression:

const isIE8 = navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

This will log either an Array or null. And yes, we can evaluate null as being false. Actually, null is a falsely value to be more precise.

But, if we double negate this:

const isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

An actual true/false boolean value will be outputed.

The double negation !! is not an actual operator, like && or ||. It is just a sequence of two negation ! signs.

The first negation converts the data (whatever it data type it may be) to a boolean, but with the opposite value. The second negation changes the boolean again to give the actual result.

// example - the long version
const x = {}; // truthy
const y = !x; // false
const z = !y; // true 

// or by using the double negation
const x = {}; // truthy
const z = !!x; // true

Advantages and disadvantages of using the !! double negation in Javascript

Well, it depends on what do you want to make more clear. For sure the actual code will look strange to someone (like me 😅) who does not know about this double negation trick.

On the other side, it will provide more clear value for the actual evaluation. The result will be just true or false. For example, you will not have to wonder anymore if an empty object is considered true or false.


const result = {};
if(result) {
    // make something
}

What is box-sizing in CSS

The default way for CSS to calculate the total needed space for an element is to sum up the follwing:
totalwidth = 2*margin + 2*border-width + 2*padding + width.

The above example assumes that all of the left - right margins, paddings, and border-width are equal.

If you have a .container with the width: 100px you will not be able to put 2 .column next to each other if you have a width: 50px and a border: 1px solid red. That is because one column will have 50px + 2*1px = 52px and your container only has 100px. While I was learning CSS this was quite an "Aha!" moment for me.

.column {
    border: 1px solid red; 
    width: 50px; // will actually take 52px 
}

.container {
    width: 100px; // will not fit 2 columns
}

But you can change this behavior by setting the box-sizing property.

You can set 2 values for box-sizing:

  • content-box ; the default option
  • border-box

If we set box-sizing: border-box this means that the padding and border-width are included in the width. This can provide provides us with better control for how much space one element will take up.

So, for border-box we will have:
totalwidth = 2*margin + (width - 2*border - 2*padding).

Please note that only the border and padding are included. The margin will still add extra space.

If you want to apply it to every element on the page, out of the box, you can just set:

*, *:before, *:after {
  box-sizing: border-box;
}

Using the CSS calc() function

The calc() is a CSS function that lets you calculate values right in your CSS. For example:

.main-content {
  width: calc(100% - 40px);
}

One of the most useful features of this function is that you can mix multiple CSS units. In our example, we used a percentage with pixels. Bun we can also use units like em, pt, rem, etc.

In 90% of the cases, I find myself using calc with the substractions sign, but you can use it along with:

  • additions by using +
  • subtractions by using -
  • multiplication by using *
  • division using by /

The operator must be wrapped in white spaces. Some operators don't work well if you don't have a white a before and after it.

// use this code 
.logo {
  height: calc(4rem - 30px);
}
// instead of this one
.logo {
  height: calc(4rem-30px);
}

It is supported in all major browsers https://caniuse.com/#feat=calc.

Using calc() with CSS variables and SASS

It works out of the box with the new CSS variables:

--text-input-width: 500px;
max-width: calc(var(--text-input-width) / 2);

Using calc() in SASS or SCSS

For SASS variables you will have to interpolate the value in the calc() function:

$body_padding}: 20px;
 height: calc(100% - #{$body_padding})