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

Making an element fullscreen with Javascript

I just discovered there is a new toy we can play with as web developers. The fullscreen API 😎. Let's see what it is about.

How to make an element fullscreen using Javascript?

Making an element fullscreen with JS is pretty straightforward. After we get its reference we just need to call requestFullscreen().

const el = document.getElementById('element'); 
el.requestFullscreen();

Keep in mind that there may be a case to use prefixes for some browsers. More details here.

How to close a fullscreen element?

In order to revert a fullscreen element to its initial state we just need to call exitFullscreen() on the element.

How to track if an element is fullscreen or not?

We have two options to track if there is a full-screen element. The first one will be to use the fullscreenchange event.

document.addEventListener('fullscreenchange', () => {
  if (document.fullscreenElement)
    alert('We are in fullscreen mode !!!')
  else
    alert('No fullscreen here !!!')
})

The second one is to use the return a promise from requestFullscreen. However, keep in mind that this one does not work in some browsers 😞, so it may be a safer bet to use the fullscreenchange event.

el.addEventListener('click', () => {
    const p = el.mozRequestFullScreen();
    p.then(() => {console.log('full screen')});
});

How do we style a fullscreen element?

If you want your element to look different when it is fullscreen, we have the :fullscreen pseudo selector:

.element:fullscreen {
    // rules here
}

And here is a full codepen to play with the fullscreen API:

See the Pen
FLS
by JS Craft (@js-craft)
on
CodePen.

CSS how to change the color of the line in underlined text

How to make a text underlined in CSS it's pretty clear. You just add text-decoration: underline; and that's pretty much it.

But there is more we can do with text-decoration.

In CSS we can use:

  • text-decoration-color to set the decoration color
  • text-decoration-style and text-decoration-line to change decoration style

Below there are a few examples of these properties in action:

See the Pen
text-decoration
by JS Craft (@js-craft)
on CodePen.

There is also a text-decoration-thickness property but with a weak browser support.

Also if you want to see some more complicated text-decoration styles and animations you can take a look at this code pen.

Know your size – CSS Units Explained: Part 2 REMs and EMs

You can see here the first part of this article: CSS Units Explained: Part 1 pixels, percentages and viewpoints units.

In CSS REM comes to the Root EM, where EM is a term borrowed from the typography world. It refers to a unit that allows setting the font-size of an element relative to the font-size of its parent 🤯.

Anyways, I promise that things will easier after we see these concepts in code.

Let's start with REM, the Root EM. How it works is that you define a font size for the body, and that font-size becomes the base unit of measure:

body { font-size: 18px; }
p {line-height: 2rem; } // 36px
h1 {margin-bottom: 3rem; } // 54px
.hero {border: 1px solid 0.5rem} // 9px

It's quite nice because if we move to a smaller screen it's enough to update just the font-size of the body all changes. All is relative to the base font-size.

On the other size, EM it's relative to the font-size of the parent container. Let's take the following code

.grid { font-size: 20px; } 
.grid .grid-cell { font-size: 1.5em; }
/* the .grid-cell will have a font-size of 20px * 1.5 = 30px 
it's the same as saying: font-size: 150%; */

But there is a small gotcha with this em. If em units are used on other properties than font-size, then the value is relative to the element’s own font-size.

So let's take again the previous code, and add a line-height prop:

.grid { font-size: 20px; } 
.grid .grid-cell { 
    font-size: 1.5em; // 30px 
    line-height: 2em;
    /* WARNING: the line-height will be 30px * 2 = 60px */
}

Another gotcha with em is the cascading effect. If we have this CSS:

.container { font-size: 10px; } 
.child { font-size: 2em; }

We can run into strange situations if we have some markup like this one:

<div class="container"> 
    I'm 10px; all good
    <div class="child"> 
        I'm 20px, as expected 
        <div class="child"> 
            I'm 40px, kind of big 
            <div class="child"> 
                I'm 80px, too big! 
                <!-- and getting bigger -->
            </div>
        </div>
    </div> 
</div>

There are cases were used with care em can provide us with a lot of flexibility and fluency. But, to be honest, overall I prefer REM for its predictability and consistency 🙂

Using the CSS @media prefers queries

I was listening to an episode of the CSS podcast and found out there are some cool things we have access be using @media prefers queries. Let's see them one by one:

  • prefers-color-scheme may be the best known of all of them. It allows us to set a coll dark mode for our app or site:
@media (prefers-color-scheme: dark) {
    background-color: black;
    color: white; 
}

@media (prefers-color-scheme: light) {
    background-color: white;
    color: black; 
}

As a side note, Lea Verou has a coll article about how you can easily add a dark mode by using CSS custom properties and hsl.

  • prefers-reduced-data this is a coll one I was not aware of. It's great because we can use it to load less costly assets (fonts, images etc) if the user has set this option to reduce.
@media (prefers-reduced-data: reduce) {
    .hero {
        background-img: url(smaller-size-img.jpeg);
    }
}

What is the :is() CSS pseudo-selector and how it is helpful

The :is() gets a list of arguments and applies the given rules to the all elements that are matching on of the selectors in the list. For example:

p:is(.main, .front) {
    font-weight: bold;
}
/* will make bold any p element that 
has at least a class of main or front */

This is a less verbose way of writing a list of CSS selectors.

p.main, 
p.front {
    font-weight: bold;
}

We can pass it anything, not just classes. We can use it in conjunction with ids, classes, tags etc.

:is(h1, h2) {....}
.login:is(div, #main, .invaid) {...}

The specificity will equal that of the passed selector with the highest specificity. So, :is(#main, div) will have the specificity of the #main - 1.0.0 and :is(h1, form) will have a specificity of 0.0.1.

Also one cool thing about the :is() selector is that it will work even if one argument is not valid. As the opposite of the classical way of writing CSS when having one invalid selector will cancel the full list.

p, 777 {...};
/* will not work not even for the p elements*/
:is (p, 777) {....}
/* will not work for the p elements*/

This makes it great to be used within selectors that are not yet fully supported in all browsers.

:is(p, webkit-unsuported-suff-here) {...}
/*will still work for the p elements*/ 

The cross-browser support is pretty good.

Using the delete keyword in Javascript to remove object keys

Let's say we have the following javascript object:

const myCat = {
    name: 'Achile',
    age: 2
}

We want to fully remove one of its properties. I've found that the easiest way to make this is by using the delete keyword.

delete myCat.age;  
// or delete myCat["age"]
// now the myCat obj is just { name: 'Achile'}

Also, the delete operator will return a boolean which will tell if the deletion was successful:

if (delete myCat.age) {
    alert("The cat had an age attr and it was removed");
}

You can go into more complicated stuff as Todd Motto writes here.

Check out the below codepen for a full example:

See the Pen
Delete Keyword
by JS Craft (@js-craft)
on CodePen.

The best two things I use to improve my productivity and work happiness

I think I've first seen this formula in the book Deep Work by Call Newport.

things_done = time * quality_of_focus. 

This article will focus on the second part of that equation.

Improving your capacity to focus is not just about getting things done, but much more about personal happiness.

I've seen that trying to get something done while jumping from one digital distraction to another is a clear formula for getting me frustrated and running my day. On the opposite side, starting my day with a good interval of about 3-4 hours where I get all the important stuff done leaves me with a nice feeling of accomplishment and a full day ahead to enjoy.

And yes, the biggest enemy of focus is distractions.

Over the years, the main tools I've discovered to work when it comes to focusing and eliminating distractions are:

  1. the Pomodoro technique. I use a free app for Mac, called beFocused, to work in sets of 25 mins. In my mind is something like "ok brain, please focus on this task for these 25 mins and after that, you can wander around to what whatever you want for about 10 min." I've discovered that having about 5 to 8 of these focused intervals per day is enough to get the important coding stuff done. I usually have them in the morning and the rest of the workday can be spent on meetings, administrative tasks, and others.

  2. buying a subscription to the Freedom app was maybe the highest ROI money that I've spent. I think there are also some free alternatives. What this app does is block access to a list of sites I consider distracting. I have it set to start automatically between 8am and 2p. During this time I don't have any access to sites like Youtube, Twitter, news, Amazon. Not even for one quick glance 🙂 Whenever I have seen I am on a site that steals my time from the important stuff I just add it to the list. Just coding, learning, and getting stuff done. And it's so worth it.

Of course, there are many other small things but overall I think these two tricks are delivering about 80% of the results.

Also maybe a good idea to check some of the books of Call Newport. Besides the techniques and tools, they are great for giving a specific way of seeing things and your relationship with work. So good they can't ignore you and Deep work in special.

BTW, if it's the first time you hear about Call Newport I would recommend this podcast. It was the interview that got me hooked on his work. Cheers!

Know your size – CSS Units Explained: Part 1 pixels, percentages and viewpoints units

There are many options for which units to use to define the size of various CSS properties. But I found myself using just about 20% of them in 80% of the cases. No reference to the Pareto principle 🙂

I think the ones that I use the most are:

  • unit based: pixels(px), percentage (%) and viewport units (vw and vh)
  • based on font-size: rem and em; more about them here
  • flexbox and css grid specific:fr

Comparing pixels vs percentage vs viewport units

Let's take the following example:

  • the first element has a fixed width of 75pixles
  • the second is set to a relative width of 50% from the available space of the parent
  • and the third one has a width of 100vh, meaning it will be 100% of the viewport width

The differences are becoming clear when we move the same elements in a container that is also set to be at 50% from the width of the body. See the red container.

While the first element will keep it's fixed width of 75px the second one will adapt its width based on the width of the container. Now, given the fact that the width of the container is half the width of the body, the second element will end up with a width of 25% from the body (50% from 50%).

However, even it the last element with a width of 100vh (viewport width) may be interpreted as relative - 100% of something - that something is the viewport width meaning that it will not matter how long the container is. It will take into account just the width of the full screen.

By the way, regarding the viewport size, we also have the vh - viewport hight as a complementary dimension. Even though the vh is usually used to define the height of elements, we can also make some funny associations like:

.my-element {
    width: 50vh;
}
/* can be used to make some aspect ratio tricks */

What are the vmax and vmax units

Speaking of the viewport units, with vmin, we size as a percentage of the smallest between the width or the height of the viewport, and with vmax, we size as a percentage of the largest between the two.

So, for example, that our viewport is 800px wide and 600px tall, if we set element to have a width of 50vmin, it’ll be 50% of the height (300px).

The vmax will select the bigest value btweeen the width and the height of the screen.

Below is the full codepen for this example. Stay tuned, as in the next article we will see the difference between using the em and rem units.

See the Pen
ZEQRMVR
by JS Craft (@js-craft)
on CodePen.

Function.lenght will tell you the number of the required arguments for a Javascript function

Just found out that any javascript function has a lenght property. It will return how many arguments are mandatory for that function:

const myFunction = (a, b, c) => {}
console.log(myFunction.length) // 3

Of course that if we provide a default value for an argument it will not be considered mandatory:

const myFunction = (a, b, c = 'some value') => {}
console.log(myFunction.length) // 2

Also, using the spread syntax will not count as a mandatory parameter.

const myFunction = ( operation, ...numbers ) => {}
console.log(myFunction.length) // 1

Not sure how useful this is daily but it's a fun trick to know. Javascript ... the forever surprising language 😀

Building a layout with CSS Grid video series: Part 4 – Centering items in CSS grid and using flexbox

This will be a shorter lesson. Its scope is to show how we can center the contents in a grid cell and also how we can combine CSS grid with any other type of layout manager.

Also, you can check the other screencast series about Build a game with React part 1 and my full video course about React on Skillshare.