Short tricks of HTML, CSS and JavaScript II
Tags: html, css, javascript, beginners
Published: 2022-11-14 19:36:01

---
title: Short tricks of HTML, CSS and JavaScript II
published: true
description: A modern list of HTML, CSS and JavaScript How Tos with basic concepts for everyday use. Feel free to comment your own approaches :)
tags: html, css, javascript, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5liowu928ryy7ruejtm5.png
---
This article was originally published on [medium.com](https://medium.com/@gengns/short-tricks-of-html-css-and-javascript-ii-39de05644d73)

A modern list of HTML, CSS and JavaScript How Tos for everyday use. Feel free to comment your own approaches :)

This is the second part, if you missed the previous one: [Short tricks of HTML, CSS and JavaScript](https://dev.to/gengns/short-tricks-of-html-css-and-javascript-582g)

## Access last element in Array
*JS*
```js
[1, 2, 3].at(-1)
```
It would be really nice to have `[1, 2, 3][-1]`

## Horizontal and vertical center
The easiest way to center anything.
*CSS*
```css
body {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
}
div {
  background-color: grey;
  width: 100px;
  height: 100px;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/vk1he7zt/).


## Date to local ISO string
*JS*
```js
new Date().toLocaleString('sv')
```
Sweden hack.


## Lazy loading images and iframes
Defer loading of images/iframes that are off-screen until the user scrolls near them.
*HTML*
```html
<img src="image.webp" loading="lazy">
<iframe src="game.html" loading="lazy"></iframe>
```


## Get string after last specific character
*JS*
```js
'filename.pdf'.split('.').pop()
```


## HTML range value
Shortest version without `form`, `min` or external JavaScript.
*HTML*
```html
<input type="range" value="0" max="10" oninput="num.value = this.value">
<output id="num">0</output>
```
View on JSFiddle [here](https://jsfiddle.net/gengns/vrbudx17/).


## Copy to clipboard
*JS*
```js
navigator.clipboard.writeText('Mr Robot')
```


## Reset all CSS
*CSS*
```css
* {
  all: unset;
}
```
You can use it with any selector.


## Get month name
*JS*
```js
const today = new Date()
today.toLocaleString('default', { month: 'long' })
```
You can set any language you want instead of browser's `default` language.


## Embedding PDF files into HTML
*HTML*
```html
<object type="application/pdf" data="https://your_file.pdf">
  <iframe src="https://docs.google.com/gview?embedded=true&url=https://your_file.pdf"/>
</object>
```
Use `object` with `iframe` fallback to support all mobile browsers.
View on JSFiddle [here](https://jsfiddle.net/gengns/txh3v5y8/).


## Flip an image
*CSS*
```css
img {
  transform: scaleX(-1); /* flip horizontally */
}
```
Use `scaleY(-1)` to flip vertically.


## Shuffle an array
*JS*
```js
array.sort(() => 0.5 - Math.random())
```


## Select images with not `alt` attribute
*CSS*
```css
img:not([alt]) {
  border: 2px solid red;
}
```


## Detect dark mode
*JS*
```js
window.matchMedia('(prefers-color-scheme: dark)').matches
```


## Accept only specific files in an input
*HTML*
```html
<input type="file" accept="image/*"> <!-- only images -->
<input type="file" accept=".pdf, .odt"> <!-- only pdf and odt -->
```


## Deep cloning an object
Assuming you don't have functions inside you can use JSON methods.
*JS*
```js
JSON.parse(JSON.stringify(object))
```


## Progress bar
You already have a native component for that.
*HTML*
```html
<progress value=".7">Progress</progress>
```


## Smooth scroll behavior
*CSS*
```css
html {
  scroll-behavior: smooth;
}
```


## Detect if your file is an image
*JS*
```js
file.type.includes('image')
```


## Automatic email validation
Just place your email `input` inside a `form`.
*HTML*
```html
<form>
  <input type="email" placeholder="name@company.com">
</form>
```
View on JSFiddle [here](https://jsfiddle.net/gengns/v0bhsxe1/).


## Transform image to WEBP format
Easier than you think using HTML5 `canvas`, `blob` and `file` rename trick to run it back into a file.
*JS*
```js
function transform_to_WEBP(file) {
 return new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = image.naturalWidth
      canvas.height = image.naturalHeight
      canvas.getContext('2d').drawImage(image, 0, 0)
      canvas.toBlob(blob => 
        resolve(new File([blob], 'filename.webp'))
      , 'image/webp')
    }
    image.src = URL.createObjectURL(file)
  })

```
We use a `promise` because loading the file takes time.


## Lazy rendering anything
`content-visibility` is a CSS property that controls whether and when an element's content is rendered. It only renders the content of an off-screen component when it becomes on-screen.
*CSS*
```css
.element {
  content-visibility: hidden;
}
```


## Clear all cookies
*JS*
```js
document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))
```


## Don't show Material Icon text when loading font
We need to change `@font-face` declaration on the server and luckily we can use an API for modifying the `font-display`.
*CSS*
```html
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block">
```


## Get CSS Variable in JS
*JS*
```js
getComputedStyle(document.documentElement)
  .getPropertyValue('--my-variable-name')
```


## Debug an Android PWA
1. Allow USB debugging in your device and open your PWA.
2. Install Android Debug Tools and check for devices.
3. Open Chrome (Chromium) and go to `chrome://inspect/#devices`

*Bash*
```
sudo apt install android-tools-adb android-tools-fastboot
adb devices
```


## Analyse performance of pieces of your code
*JS*
```js
console.time()
// your code
console.timeEnd()
```


## Capitalize first letter
*JS*
```js
str.charAt(0).toUpperCase() + str.slice(1)
```


## Number of days between 2 days
*JS*
```js
(date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
```

## Basic fade-in animation
Workaround to avoid `display: none` problems.
*CSS*
```css
h1 {
  animation: fade 1s ease-in 3s forwards;
  pointer-events: none;
  opacity: 0;
}
@keyframes fade {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/Ls8w6ukp/).



## Get selected text
*JS*
```js
window.getSelection().toString()
```


## Allow user to resize any element
*CSS*
```css
div {
  overflow: auto;
  resize: both;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/m4k8qvtj/).


## Check valid date
*JS*
```js
(new Date(date) != 'Invalid Date') && !isNaN(new Date(date))
```


## HTML and CSS only interactive carousel
Snapping, clickable and responsive images in a carousel effect without JavaScript.
*HTML*
```html
<g-carousel>
  <g-images>
     <a href="#b"><img id="a" src="https://source.unsplash.com/random/800x400?sig=1"></a>
     <a href="#c"><img id="b" src="https://source.unsplash.com/random/800x400?sig=2"></a>
     <a href="#a"><img id="c" src="https://source.unsplash.com/random/800x400?sig=3"></a>
  </g-images>
</g-carousel>
```

*CSS*
```css
g-carousel {
  display: block;
  width: 100%;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
}
a {
  display: contents;
}
g-images {
  display: flex;
  width: calc(100% * 3);
}
img {
  width: 100%;
  scroll-snap-align: center;
}
```

View on JSFiddle [here](https://jsfiddle.net/gengns/4qc5x7Lo/).


***


# Geek stuff
★ Do you love HTML, CSS and JavaScript as I do? ^^ Don't forget to check [my geek clothing about web development](https://www.zazzle.com/store/programming_t_shirts) ;P