Short tricks of HTML, CSS and JavaScript
Tags: html, css, javascript, beginners
Published: 2020-05-25 17:59:16

---
title: Short tricks of HTML, CSS and JavaScript
published: true
description: A nice 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/i/vikgj9pssaffio4xbb7j.png
---
This article was originally published on [medium.com] (https://medium.com/@gengns/short-tricks-of-html-css-and-javascript-85b567716945)

*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*
```css
.disabled {
  filter: grayscale(1);
  pointer-events: none;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/1z21pmez/).


## Split an array into chunks without mutability
*JS*
```javascript
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:
```javascript
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](https://jsfiddle.net/gengns/yh3q8zkn/).


## 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*
```html
<input type="datetime-local">
<button>Save</button>
<button>Load</button>
```
*JS*
```javascript
$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](http://jsfiddle.net/gengns/jtavp7wk/).

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*
```javascript
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](http://jsfiddle.net/gengns/3L15g6hc/).


## Rename when destructuring
We are going to rename time property while sorting our array of objects.
*JS*
```javascript
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](http://jsfiddle.net/gengns/z1boo40u/).


## 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*
```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](http://jsfiddle.net/gengns/o1t06jaj/).

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*
```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*
```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](http://jsfiddle.net/gengns/fxd0gk3j/).

I would recommend you to do these [examples](https://gridbyexample.com/examples/).

Fall in love with Grid Templates like I did ❤


## Move parts of the user interface without loss of interaction
*HTML*
```html
<ul>
  <li>
    <button id="up">Up</button>
    <button id="down">Down</button>
  </li>
  <li>Nothing</li>
  <li>Nothing</li>
</ul>
```

*JS*
```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](http://jsfiddle.net/gengns/f2654y1h/).


## 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*
```html
<div>
  <input type="number" min="0" max="23" placeholder="23">:
  <input type="number" min="0" max="59" placeholder="00">
</div>
```
*CSS*
```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*
```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](http://jsfiddle.net/gengns/xcgjz9xt/).


## Loop n times without mutable variables
*JS*
```javascript
[...Array(10).keys()]
  .reduce((sum, e) => sum + `<li>${e}</li>`, '')
```
also like this:
```javascript
[...Array(10)]
  .reduce((sum, _, i) => sum + `<li>${i}</li>`, '')
```
View on JSFiddle [here](http://jsfiddle.net/gengns/LdLbto1z/).


## Horizontal and vertical center
Forget about any complicated way, just use Flexbox and set up horizontal center and vertical center in the container.

*CSS*
```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](http://jsfiddle.net/gengns/5g4sxfx8/).


## Asynchronous fetch
Using `fetch()` with asyncronous functions.

*JS*
```javascript
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](http://jsfiddle.net/gengns/x0tjh6ef/).

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*
```html
<footer>
  <div>
    <button>Button A</button>
    <button>Button B</Button>
  </div>
  <div>
    <button>Button C</button>
    <button>Button D</button>
  </div>
</footer>
```
*CSS*
```css
footer {
  display: flex;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/7m97o123/).

## 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*
```javascript
document.querySelector(`div:nth-child(${random})`).scrollIntoView()
```
View on JSFiddle [here](https://jsfiddle.net/gengns/k5raku7c/).


## Flattening arrays of objects
*JS*
```javascript
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](http://gengns.com/flattening-arrays-of-objects/) (I did also some time consuming test using jsPerf).

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

Remember, in case you want to flat arrays of arrays you can do it easily with `flat()`.

```javascript
[1, 2, [3, 4, [5, 6]]].flat(Infinity)
```


## Nesting arrays of objects
Returns an array of n elements filled with content:
*JS*
```javascript
let get_array = (n, content) => Array(n).fill(content)
```
Returns an object with a name property that has a content value:
```javascript
let get_object = (name, content) => 
  Object.defineProperty({}, name, {value: content})
```
3 levels of arrays with objects (nested)
```javascript
a = 
get_array(3, get_object('b', 
  get_array(6, get_object('c', 
    get_array(3, {})
  ))
))
```
View on JSFiddle [here](https://jsfiddle.net/gengns/kkpfeedg/).


## Array without duplicate values
*JS*
```javascript
const array = [1, 2, 3, 3, 3, 2, 1]
```
The Set strategy:
```javascript
[...new Set(array)]
```
The filter strategy (easier to figure out but slower):
```javascript
array.filter((elem, index) => index == array.indexOf(elem))
```
View on JSFiddle [here](https://jsfiddle.net/gengns/znj9q0rz/).

Remember, `Array.from(iterableObj) = [...iterableObj]`


## HTML input with units
*HTML*
```html
<span><input type="number" min="0" value="50">€</span>
```
*CSS*
```css
span {
  background: white;
  border: 1px solid #e8e8e8;
}
input {
  background: inherit;
  outline: none;
  border: none;
  padding: 0 5px;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/e8uxszqc/).


## Responsive background loop video
*HTML*
```html
<video autoplay loop poster="https://website/video.jpg">
  <source src="http://website/video.webm">
</video>
```
*CSS*
```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](https://jsfiddle.net/gengns/cyyno5my/).


## How to print a specific HTML element
I would like to have something like this:
```javascript
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*
```css
@media print {
  body.print-element *:not(.print) {
    display: none;
  }
}
```
*JS*
```javascript
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](https://jsfiddle.net/gengns/d50m8ztu/).


## 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*
```html
<input id="password" type="password" placeholder="type password...">
<button id="view-password"></button>
<button id="generate-password">↻</button>
```
View or hide password:
*JS*
```javascript
$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:
```javascript
$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](https://jsfiddle.net/gengns/pvzg1d6u/).

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*
```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*
```javascript
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:

```html
<ul><li></li><li></li></ul>
```

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


## 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*
```css
div {
  width: 60vw;
  height: 60vw;
  margin: 20vh auto;
  background-color: #774C60;
}
```
View on JSFiddle [here](https://jsfiddle.net/gengns/89h40bjf/).


## 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*
```javascript
const width = e.currentTarget.clientWidth
```
Absolute position of the mouse cursor from the circle center:
```javascript
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:
```javascript
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*
```javascript
$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](https://jsfiddle.net/gengns/dojqdfdh/).


## Counter with a reset using closures
Set up a basic counter with a closure and some external accessible options.

*JS*
```javascript
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](https://jsfiddle.net/gengns/rskugok2/).


## 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*
```javascript
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](https://jsfiddle.net/gengns/n5o82orb/).

Just notice in the example above that we could make it more efficient creating nodes and using `appendChild()`.


## Material icons
*HTML*
```html
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
 rel="stylesheet">
 
<i class="material-icons">face</i>
```

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


## 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*
```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](https://jsfiddle.net/gengns/wng8a8ju/).


## Export HTML table to CSV file
Imagine you have an HTML table and you want to download it as a CSV table.

*HTML*
```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*
```javascript
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:

```javascript
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](https://jsfiddle.net/gengns/j1jm2tjx/).


## 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*
```javascript
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](http://jsfiddle.net/gengns/8vaj5whh/).


## 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*
```javascript
// 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.

```javascript
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:
```javascript
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain): `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*
```html
<body onload="foo()">
```

*JS*
```javascript
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*
```javascript
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](https://www.zazzle.com/store/programming_t_shirts) ;P