DEV Community

Cover image for Short tricks of HTML, CSS and JavaScript II
gengns
gengns

Posted on

Short tricks of HTML, CSS and JavaScript II

This article was originally published on medium.com

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

Access last element in Array

JS

[1, 2, 3].at(-1)
Enter fullscreen mode Exit fullscreen mode

It would be really nice to have [1, 2, 3][-1]

Horizontal and vertical center

The easiest way to center anything.
CSS

body {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
}
div {
  background-color: grey;
  width: 100px;
  height: 100px;
}
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.

Date to local ISO string

JS

new Date().toLocaleString('sv')
Enter fullscreen mode Exit fullscreen mode

Sweden hack.

Lazy loading images and iframes

Defer loading of images/iframes that are off-screen until the user scrolls near them.
HTML

<img src="image.webp" loading="lazy">
<iframe src="game.html" loading="lazy"></iframe>
Enter fullscreen mode Exit fullscreen mode

Get string after last specific character

JS

'filename.pdf'.split('.').pop()
Enter fullscreen mode Exit fullscreen mode

HTML range value

Shortest version without form, min or external JavaScript.
HTML

<input type="range" value="0" max="10" oninput="num.value = this.value">
<output id="num">0</output>
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.

Copy to clipboard

JS

navigator.clipboard.writeText('Mr Robot')
Enter fullscreen mode Exit fullscreen mode

Reset all CSS

CSS

* {
  all: unset;
}
Enter fullscreen mode Exit fullscreen mode

You can use it with any selector.

Get month name

JS

const today = new Date()
today.toLocaleString('default', { month: 'long' })
Enter fullscreen mode Exit fullscreen mode

You can set any language you want instead of browser's default language.

Embedding PDF files into 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>
Enter fullscreen mode Exit fullscreen mode

Use object with iframe fallback to support all mobile browsers.
View on JSFiddle here.

Flip an image

CSS

img {
  transform: scaleX(-1); /* flip horizontally */
}
Enter fullscreen mode Exit fullscreen mode

Use scaleY(-1) to flip vertically.

Shuffle an array

JS

array.sort(() => 0.5 - Math.random())
Enter fullscreen mode Exit fullscreen mode

Select images with not alt attribute

CSS

img:not([alt]) {
  border: 2px solid red;
}
Enter fullscreen mode Exit fullscreen mode

Detect dark mode

JS

window.matchMedia('(prefers-color-scheme: dark)').matches
Enter fullscreen mode Exit fullscreen mode

Accept only specific files in an input

HTML

<input type="file" accept="image/*"> <!-- only images -->
<input type="file" accept=".pdf, .odt"> <!-- only pdf and odt -->
Enter fullscreen mode Exit fullscreen mode

Deep cloning an object

Assuming you don't have functions inside you can use JSON methods.
JS

JSON.parse(JSON.stringify(object))
Enter fullscreen mode Exit fullscreen mode

Progress bar

You already have a native component for that.
HTML

<progress value=".7">Progress</progress>
Enter fullscreen mode Exit fullscreen mode

Smooth scrollΒ behavior

CSS

html {
  scroll-behavior: smooth;
}
Enter fullscreen mode Exit fullscreen mode

Detect if your file is an image

JS

file.type.includes('image')
Enter fullscreen mode Exit fullscreen mode

Automatic email validation

Just place your email input inside a form.
HTML

<form>
  <input type="email" placeholder="name@company.com">
</form>
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.

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

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)
  })

Enter fullscreen mode Exit fullscreen mode

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

.element {
  content-visibility: hidden;
}
Enter fullscreen mode Exit fullscreen mode

Clear all cookies

JS

document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))
Enter fullscreen mode Exit fullscreen mode

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

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block">
Enter fullscreen mode Exit fullscreen mode

Get CSS Variable in JS

JS

getComputedStyle(document.documentElement)
  .getPropertyValue('--my-variable-name')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Analyse performance of pieces of your code

JS

console.time()
// your code
console.timeEnd()
Enter fullscreen mode Exit fullscreen mode

Capitalize first letter

JS

str.charAt(0).toUpperCase() + str.slice(1)
Enter fullscreen mode Exit fullscreen mode

Number of days between 2 days

JS

(date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
Enter fullscreen mode Exit fullscreen mode

Basic fade-in animation

Workaround to avoid display: none problems.
CSS

h1 {
  animation: fade 1s ease-in 3s forwards;
  pointer-events: none;
  opacity: 0;
}
@keyframes fade {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.

Get selected text

JS

window.getSelection().toString()
Enter fullscreen mode Exit fullscreen mode

Allow user to resize anyΒ element

CSS

div {
  overflow: auto;
  resize: both;
}
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.

Check valid date

JS

(new Date(date) != 'Invalid Date') && !isNaN(new Date(date))
Enter fullscreen mode Exit fullscreen mode

HTML and CSS only interactive carousel

Snapping, clickable and responsive images in a carousel effect without JavaScript.
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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

View on JSFiddle here.


Geek stuff

β˜… Do you love HTML, CSS and JavaScript as I do? ^^ Don't forget to check my geek clothing about web development ;P

Top comments (1)

Collapse
 
sohadalmadhoon profile image
Sohad Almadhoon πŸ‘©πŸΌβ€πŸ’»

Great!!!!