Programming

Vanilla Javascript Tricks

Published on August 4, 2016

Trigger A Window Resize

I needed this to have my Chart.js charts redraw themselves due to some odd sizings within dynamically presented flexbox containers.

window.dispatchEvent(new Event('resize'));

Remove UTM fragments from URL

This helps to remove the ugly and verbose url fragments in order to log the referrer, medium etc. for Universal Tag Manager

function removeUTM() {
  const loc = window.location;

  if (loc.search.includes('utm')) {
    if (window.history.replaceState) {
      history.replaceState({}, '', loc.pathname)
    } else {
      loc.hash = ''
    }
  }
}

ga(removeUTM)

Convert DOM Node List to Array

While a Node List contains some simliar Array properties such as length, it is not possible to iterate through the list like an array, so we need to convert the Node List into an Array to use any native methods such as forEach. Below are methods for both ES5 and ES6.

// ES5 Method
var elementNodeList = document.querySelectorAll('.example');
var elementArray = [].slice.call(elementNodeList);
elementArray.forEach(...);

// ES6 Method
const elementArray = Array.from(document.querySelectorAll('.example'));
elementArray.forEach(...)
Share This Post
Previous Post Top New ES6 Features
Next Post Airdrop Not Working?