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)
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;
}
View on JSFiddle here.
Date to local ISO string
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
<img src="image.webp" loading="lazy">
<iframe src="game.html" loading="lazy"></iframe>
Get string after last specific character
JS
'filename.pdf'.split('.').pop()
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>
View on JSFiddle here.
Copy to clipboard
JS
navigator.clipboard.writeText('Mr Robot')
Reset all CSS
CSS
* {
all: unset;
}
You can use it with any selector.
Get month name
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
<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.
Flip an image
CSS
img {
transform: scaleX(-1); /* flip horizontally */
}
Use scaleY(-1)
to flip vertically.
Shuffle an array
JS
array.sort(() => 0.5 - Math.random())
Select images with not alt
attribute
CSS
img:not([alt]) {
border: 2px solid red;
}
Detect dark mode
JS
window.matchMedia('(prefers-color-scheme: dark)').matches
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 -->
Deep cloning an object
Assuming you don't have functions inside you can use JSON methods.
JS
JSON.parse(JSON.stringify(object))
Progress bar
You already have a native component for that.
HTML
<progress value=".7">Progress</progress>
Smooth scrollΒ behavior
CSS
html {
scroll-behavior: smooth;
}
Detect if your file is an image
JS
file.type.includes('image')
Automatic email validation
Just place your email input
inside a form
.
HTML
<form>
<input type="email" placeholder="name@company.com">
</form>
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)
})
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;
}
Clear all cookies
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
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block">
Get CSS Variable in JS
JS
getComputedStyle(document.documentElement)
.getPropertyValue('--my-variable-name')
Debug an Android PWA
- Allow USB debugging in your device and open your PWA.
- Install Android Debug Tools and check for devices.
- 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
console.time()
// your code
console.timeEnd()
Capitalize first letter
JS
str.charAt(0).toUpperCase() + str.slice(1)
Number of days between 2 days
JS
(date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
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;
}
}
View on JSFiddle here.
Get selected text
JS
window.getSelection().toString()
Allow user to resize anyΒ element
CSS
div {
overflow: auto;
resize: both;
}
View on JSFiddle here.
Check valid date
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
<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
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.
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)
Great!!!!