Useful Javascript snippets

Test if an element exists before using it

var someEle = document.querySelector("#some_id"); 
if(typeof (someEle) != "undefined" && someEle != null){
    
}

Vanilla JS equivalent to jQuery.ready()

// vanilla js equivalent of jquery.ready
document.addEventListener("DOMContentLoaded", function() {
  // do stuff on page load
});

 

Quickly Enable/Disable Javascript (Chrome)

  • open developer tools
  • Cmd + Shift + p
  • type: javascript
  • click enable / disable Javascript

(writable) Global var

 

(writable) Global var (hack) in ES6 accessible from any file

https://stackoverflow.com/questions/33875322/javascript-and-es6-global-variables

An important note on Javascript modules and scope

module features are imported into the scope of a single script — they aren’t available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won’t be able to access them from the JavaScript console, for example.  more here: Modules Mozilla

e.g.

import * as cook from './cookie-functions.js';

Everything imported from cookie-functions.js is available/visile only in the script where the import is.