Short tricks of HTML, CSS and JavaScript
gengns
Posted on May 25, 2020
This article was originally published on medium.com
A nice list of HTML, CSS and JavaScript How Tos with basic concepts for everyday use. Feel free to comment your own approaches :)
Disabling everything with CSS
CSS
.disabled {
filter: grayscale(1);
pointer-events: none;
}
View on JSFiddle here.
Split an array into chunks without mutability
JS
const array = [1, 2, 3, 4]
const size = 3
const new_array = array.reduce((acc, a, i) => {
i % size ? acc[parseInt(i / size)].push(a) : acc.push([a])
return acc
}, [])
or even shorter:
const new_array = array.reduce((acc, a, i) =>
i % size ? acc : [...acc, array.slice(i, i + size)], [])
Remember, start using const
, if you need to change its value then use let
and avoid as much as possible var
.
View on JSFiddle here.
Saving and loading dates
Save your datetime always in UTC ISO and load it to the user interface using local ISO. Use native widgets to avoid facing date format preferences (middle endian, little endian, etc)
HTML
<input type="datetime-local">
<button>Save</button>
<button>Load</button>
JS
$button_save.onclick = () =>
localStorage.setItem('datetime', $input.value &&
new Date($input.value).toISOString())
$button_load.onclick = () =>
$input.value = localStorage.getItem('datetime') &&
toLocalISOString(new Date(localStorage.getItem('datetime')))
.slice(0, -8)
function toLocalISOString(d) {
const offset = d.getTimezoneOffset()
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes() - offset,
d.getSeconds(),
d.getMilliseconds()).toISOString()
}
View on JSFiddle here.
I recommend using sessionStorage
and localStorage
. Do not abuse cookies if they are not strictly necessary. If you need more local storage you can use IndexedDB.
Select HTML table columns by clicking on the headers
JS
document.querySelectorAll('th').forEach($th =>
$th.onclick = event => {
document.querySelectorAll(`td:nth-of-type(${event.currentTarget
.cellIndex + 1})`)
.forEach($td => $td.classList.toggle('selected'))
})
Remember, onclick
always overwrites the previous function (in case there was any), use addEventListener()
for multiple functions.
View on JSFiddle here.
Rename when destructuring
We are going to rename time property while sorting our array of objects.
JS
let times = [
{name:'dog', time: '10:23'},
{name: 'laundry', time: '09:34'},
{name: 'work', time: '11:00'}]
times.sort(({ time: a }, { time: b }) => a < b ? -1 : a > b ? 1 : 0)
Remember, sort()
changes the orginal array.
View on JSFiddle here.
Autocomplete dropdown
Have you ever used autocomplete dropdowns from jQuery UI or Bootstrap third party options? A complete heavyweight mess.
Luckly, we got a couple of years ago an awaited solution: Native HTML5 Autocomplete dropdown with datalist
. A lightweight standard supported in all devices.
HTML
<input list="series">
<datalist id="series">
<option value="Adventure Time">
<option value="Rick and Morty">
<option value="Game of Thrones">
<option value="Planet Earth 2">
</datalist>
View on JSFiddle here.
Save your tooling time and dependency, use as few libraries and frameworks as possible!
Real easy responsiveness with CSS Grid
CSS Grid is the easiest, cleanest and powerful way to deal with responsiveness, a completely new approach baked in the last years and ready to use.
CSS Grid changes how you used to layout your documents, instead of divitis (plenty of divs) and JavaScript to change div
positions depending on screens (what Bootstrap does nowadays), you can use pure CSS grid layouts with just the meaningful divs and independently of document source order.
You don’t need to touch HTML or JavaScript, you don’t need Bootstrap or even complex CSS rules, what you see in your CSS is what you get on your screen.
HTML
<div class="grid">
<div class="name">Name</div>
<div class="score">Score</div>
<div class="skills">Skills</div>
<div class="chart">Chart</div>
</div>
CSS
.grid {
display: grid;
grid-template-areas:
"name"
"score"
"skills"
"chart";
}
@media only screen and (min-width: 500px) {
.grid {
grid-template-areas:
"name skills"
"score skills"
"chart chart";
}
}
.name {
grid-area: name;
}
.score {
grid-area: score;
}
.skills {
grid-area: skills;
}
.chart {
grid-area: chart;
}
View on JSFiddle here.
I would recommend you to do these examples.
Fall in love with Grid Templates like I did ❤
Move parts of the user interface without loss of interaction
HTML
<ul>
<li>
<button id="up">Up</button>
<button id="down">Down</button>
</li>
<li>Nothing</li>
<li>Nothing</li>
</ul>
JS
document.querySelector('#up').onclick = e => {
const $li = e.target.parentElement
if ($li.previousElementSibling)
$li.parentElement.insertBefore($li, $li.previousElementSibling)
}
document.querySelector('#down').onclick = e => {
const $li = e.target.parentElement
if ($li.nextElementSibling)
$li.parentElement.insertBefore($li.nextElementSibling, $li)
}
Remember, target
is what triggers the event and currentTarget
is what you assigned your listener to.
View on JSFiddle here.
HTML input time with 24 hours format
Rely on native HTML widgets without depending on third party libraries. However, sometimes there are some limitations, if you have ever dealt with an HTML input
time you know what it is about, try to set up maximum or minimum hours/minutes and/or change from 12 hours format to 24 hours and viceversa. By now, a good solution to avoid headaches is to use 2 inputs of the type number and a pinch of JS.
HTML
<div>
<input type="number" min="0" max="23" placeholder="23">:
<input type="number" min="0" max="59" placeholder="00">
</div>
CSS
div {
background-color: white;
display: inline-flex;
border: 1px solid #ccc;
color: #555;
}
input {
border: none;
color: #555;
text-align: center;
width: 60px;
}
JS
document.querySelectorAll('input[type=number]')
.forEach(e => e.oninput = () => {
if (e.value.length >= 2) e.value = e.value.slice(0, 2)
if (e.value.length == 1) e.value = '0' + e.value
if (!e.value) e.value = '00'
})
Remember, ==
double comparation for equality and ===
triple one for equality and type.
If you want to check whether a variable is undefined
or not, simple use triple compartion a === undefined
and the same for null
. If you want to check whether it exists or not use typeof a != 'undefined'
.
View on JSFiddle here.
Loop n times without mutable variables
JS
[...Array(10).keys()]
.reduce((sum, e) => sum + `<li>${e}</li>`, '')
also like this:
[...Array(10)]
.reduce((sum, _, i) => sum + `<li>${i}</li>`, '')
View on JSFiddle here.
Horizontal and vertical center
Forget about any complicated way, just use Flexbox and set up horizontal center and vertical center in the container.
CSS
body {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
}
div {
background-color: #555;
width: 100px;
height: 100px;
}
View on JSFiddle here.
Asynchronous fetch
Using fetch()
with asyncronous functions.
JS
async function async_fetch(url) {
let response = await fetch(url)
return await response.json()
}
async_fetch('https://httpbin.org/ip')
.then(data => console.log(data))
.catch(error => console.log('Fetch error: ' + error))
View on JSFiddle here.
Note, as you have noticed I don’t write the ;
semicolon, that’s perfectly fine, in JavaScript the ;
is not mandatory, it doesn’t matter if you write it or not, the JS engine is going to check it and insert it if needed, just be careful with new lines that start with (
parentesis and avoid return
with the value in a diferent line.
Footer with right and left buttons
HTML
<footer>
<div>
<button>Button A</button>
<button>Button B</Button>
</div>
<div>
<button>Button C</button>
<button>Button D</button>
</div>
</footer>
CSS
footer {
display: flex;
justify-content: space-between;
position: fixed;
bottom: 0;
left: 0;
right: 0;
}
View on JSFiddle here.
Scroll into view
I have created n boxes (divs) with random colors to select one of them randomly and make it visible on the viewport. Every time you rerun the code you will see in your screen the selected box regardless of its position.
JS
document.querySelector(`div:nth-child(${random})`).scrollIntoView()
View on JSFiddle here.
Flattening arrays of objects
JS
array = alphas.map(a =>
a.gammas.map(g => g.betas)
).join()
If you want to see other different approaches using forEach
with concat
and with push
check this link (I did also some time consuming test using jsPerf).
View on JSFiddle here.
Remember, in case you want to flat arrays of arrays you can do it easily with flat()
.
[1, 2, [3, 4, [5, 6]]].flat(Infinity)
Nesting arrays of objects
Returns an array of n elements filled with content:
JS
let get_array = (n, content) => Array(n).fill(content)
Returns an object with a name property that has a content value:
let get_object = (name, content) =>
Object.defineProperty({}, name, {value: content})
3 levels of arrays with objects (nested)
a =
get_array(3, get_object('b',
get_array(6, get_object('c',
get_array(3, {})
))
))
View on JSFiddle here.
Array without duplicate values
JS
const array = [1, 2, 3, 3, 3, 2, 1]
The Set strategy:
[...new Set(array)]
The filter strategy (easier to figure out but slower):
array.filter((elem, index) => index == array.indexOf(elem))
View on JSFiddle here.
Remember, Array.from(iterableObj) = [...iterableObj]
HTML input with units
HTML
<span><input type="number" min="0" value="50">€</span>
CSS
span {
background: white;
border: 1px solid #e8e8e8;
}
input {
background: inherit;
outline: none;
border: none;
padding: 0 5px;
}
View on JSFiddle here.
Responsive background loop video
HTML
<video autoplay loop poster="https://website/video.jpg">
<source src="http://website/video.webm">
</video>
CSS
video.landscape {
width: 100vw;
height: auto;
}
video {
width: auto;
height: 100vh;
}
Remember, you can add as many sources as you want to support different video formats.
View on JSFiddle here.
How to print a specific HTML element
I would like to have something like this:
document.querySelector('div').print() // maybe in the future
At the moment of this post the standard only supports window.print()
, however we can do the trick with CSS and a little bit of JavaScript:
CSS
@media print {
body.print-element *:not(.print) {
display: none;
}
}
JS
function print_this(elem) {
document.body.classList.add('print-element')
elem.classList.add('print')
window.print()
document.body.classList.remove('print-element')
elem.classList.remove('print')
}
View on JSFiddle here.
View, hide, type and generate password
Love to make things as simple as possible xD
A hint just inside the input
, then a button
to show the password and finally another button
to generate random passwords.
HTML
<input id="password" type="password" placeholder="type password...">
<button id="view-password"></button>
<button id="generate-password">↻</button>
View or hide password:
JS
$view_password.addEventListener('click', e => {
e.currentTarget.classList.toggle('view')
if (e.currentTarget.className.includes('view'))
$password.setAttribute('type', 'text')
else $password.setAttribute('type', 'password')
})
Set a random password and make sure it’s shown:
$generate_password.addEventListener('click', () => {
$view_password.classList.add('view')
$password.setAttribute('type', 'text')
$password.value = Math.random().toString(36).slice(-8)
})
View on JSFiddle here.
Note, I personally name selector’s const
starting with a $.
Infinite previous and next selection
Select each element in a selection loop. If you go forward as soon as you finish the list of elements you will start selecting from the beginning and the same if you go in opposite direction.
HTML
<button id="previous">Previous</button>
<button id="next">Next</button>
<ul>
<li></li>
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
</ul>
JS
document.querySelector('#next').addEventListener('click', () => {
const $selected = document.querySelector('.selected')
const $next_element = $selected.nextElementSibling
if (!$next_element)
$next_element = $selected.parentElement.firstElementChild
$selected.classList.remove('selected')
$next_element.classList.add('selected')
})
Remember, use nextElementSibling
and previousElementSibling
(DOM elements) instead of nextSibling
and previousSibling
(DOM objects). A DOM Object can be anything: comments, insolated text, line breaks, etc. In our example nextSibling
would have worked if we had set all our HTML elements together without anything between then:
<ul><li></li><li></li></ul>
View on JSFiddle here.
Responsive square
I have seen many weird ways to create responsive squares, that’s why I would like to share an easy one. Go to the JSFiddle link below and play resizing the result window.
CSS
div {
width: 60vw;
height: 60vw;
margin: 20vh auto;
background-color: #774C60;
}
View on JSFiddle here.
Circle area defined by mouse click
We are going to define the area of a circle depending on where we click within a box area. We can handle this using JavaScript events, a little bit of basic maths and CSS.
Width and height are igual, it doesn’t matter which we will set for our maths:
JS
const width = e.currentTarget.clientWidth
Absolute position of the mouse cursor from the circle center:
const x = Math.abs(e.clientX — offset.left — width / 2)
const y = Math.abs(e.clientY — offset.top — width / 2)
The maximum will tell us the percent of the circle area:
percent = Math.round(2 * Math.max(x, y) * 100 / width)
$circle.style.width = percent + '%'
$circle.style.height = percent + '%'
Text Overwriting
Well, maybe you are thinking that you can just turn on your Insert key from your keyboard but what If you don’t have it or if you want to always have an overwriting mode (independently) while typing in some specific inputs and textareas. You can do it easily.
JS
$input.addEventListener('keypress', function(e) {
const cursor_pos = e.currentTarget.selectionStart
if (!e.charCode) return
$input.value = $input.value.slice(0, cursor_pos) +
$input.value.slice(cursor_pos + 1)
e.currentTarget.selectionStart =
e.currentTarget.selectionEnd =
cursor_pos
})
View on JSFiddle here.
Counter with a reset using closures
Set up a basic counter with a closure and some external accessible options.
JS
const add = (function() {
let offset = 0
return function(option) {
switch (option) {
case 0: offset = 0; break;
case 1: offset++; break;
case 2: offset — ; break;
default: throw ‘Not a valid option’;
}
console.log(offset)
}
})()
Remembler, a closure just let you keep recorded and protected your variables.
View on JSFiddle here.
Infinite scroll
Have you ever seen those automatic "Load More" while you scroll down? Did you see them on Tumblr for images, Gmail for messages or Facebook? Cool, isn’t it? The infinite scroll is an alternative for pagination and it’s everywhere. It optimizes the user experience loading data as the user required it (indirectly). You get faster loading process for pages, web, apps and it just loads what you need instead of the whole bunch. You don’t need to add extra interactions, buttons or widgets because it comes with the normal reading behaviour that you are used to: scroll down with the mouse or with the finger in a touchable screen.
JS
const $ol = document.querySelector('ol')
function load_more() {
let html = ''
for (var i = 0; i < 5; i++) html += '<li></li>'
$ol.innerHTML += html
}
$ol.addEventListener('scroll', function() {
if ($ol.scrollHeight — $ol.scrollTop == $ol.clientHeight)
load_more()
})
View on JSFiddle here.
Just notice in the example above that we could make it more efficient creating nodes and using appendChild()
.
Material icons
HTML
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<i class="material-icons">face</i>
View on JSFiddle here.
Basic CSS transition using box-shadow
Our CSS will change if the mouse is over the element with an ease-in-out transition effect (slow start and end). We are filling up the element with an inner shadow (inset)
CSS
i {
transition: all 0.5s ease-in-out;
box-shadow: 0 0 0 75px #E94F37 inset;
}
i:hover {
box-shadow: 0 0 0 4px #E94F37 inset;
color:#E94F37;
}
View on JSFiddle here.
Export HTML table to CSV file
Imagine you have an HTML table and you want to download it as a CSV table.
HTML
<table>
<tr><th>Name</th><th>Age</th><th>Country</th></tr>
<tr><td>Geronimo</td><td>26</td><td>France</td></tr>
<tr><td>Natalia</td><td>19</td><td>Spain</td></tr>
<tr><td>Silvia</td><td>32</td><td>Russia</td></tr>
</table>
First of all, you need to transform from HTML to CSV:
JS
let csv = []
let rows = document.querySelectorAll('table tr')
for (var i = 0; i < rows.length; i++) {
let row = [], cols = rows[i].querySelectorAll('td, th')
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText)
csv.push(row.join(','))
}
download_csv(csv.join('\n'), filename)
After that, you can download it using Blob
and a link:
let csvFile = new Blob([csv], {type: 'text/csv'})
let downloadLink = document.createElement('a')
downloadLink.download = filename
downloadLink.href = window.URL.createObjectURL(csvFile)
downloadLink.style.display = 'none'
document.body.appendChild(downloadLink)
downloadLink.click()
View on JSFiddle here.
Keyboard events
Use event.code
to get a human readable way of knowing which keys are pressed. Use event.key
if you want to distinguish between capital letter or not, and avoid browser shortcuts, i.e: Ctrl + P (print)
JS
document.onkeydown = event => {
switch (event.code) {
case 'ArrowDown':
$div.style.top = `${parseInt($div.style.top || 0) + step}px`
break
case 'KeyR':
if (event.altKey) $div.style.top = 0
break
}
}
View on JSFiddle here.
Short selectors like jQuery
Using JavaScript is some kind of annoying when you have to select DOM elements, in those cases we could miss jQuery because vanilla JavaScript is simply too long.
JS
// Select one element (first one)
document.querySelector('#peter')
document.querySelector('.staff')
document.querySelector('.staff').querySelector('.age')
// Select all elements
document.querySelectorAll('.staff')
We don’t like to repeat things when we are coding, if you define the next code at the beginning of your JavaScript you will be avaliable to do it similar even better than jQuery.
function $(selector) {
return document.querySelector(selector)
}
function $$(selector) {
return document.querySelectorAll(selector)
}
Element.prototype.$ = function(selector) {
return this.querySelector(selector)
}
Element.prototype.$$ = function(selector) {
return this.querySelectorAll(selector)
}
Now you can write our example shorter:
// Select one element
$('#peter')
$('.staff')
$('.staff').$('.age')
// Select all elements
$$('.staff')
It’s easy to keep in mind because $ behaves like jQuery with CSS selectors and $$ does the same but it allows you to select multiple elements. The first one returns the first element found and the second one a list of elements.
Just one more thing, you cannot use jQuery with this code because jQuery use $ too, if you need it you have to change the $ in our code for another thing, ie: qS.
Remember, in JavaScript we have something better than classes: prototype
. It doesn’t matter if you use class
, under the hood is using prototype
.
Which is the different between property and attribute?
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
HTML
<body onload="foo()">
JS
document.body.onload = foo
Avoid switch statement when you don’t need logic
Arrays are faster, in the next example if you want to now which is the nineth month you can just code months[9]
.
JS
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
Geek stuff
★ Do you love HTML, CSS and JavaScript as I do? ^^ Don't forget to check my geek clothing about web development ;P
Posted on May 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.