Skip to content

Instantly share code, notes, and snippets.

@filiptronicek
Last active October 9, 2020 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filiptronicek/243ae9ac0b45f173604a1d3f58e7240b to your computer and use it in GitHub Desktop.
Save filiptronicek/243ae9ac0b45f173604a1d3f58e7240b to your computer and use it in GitHub Desktop.
Converting from jQuery to vanilla JS

$()

You can define most of the queries by:

window.$ = document.querySelectorAll.bind(document)

(https://stackoverflow.com/questions/978799/is-there-an-easy-way-to-convert-jquery-code-to-javascript)

$(window).height() and $(window).width()

You can get the height of the window by

const w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],

width = w.innerWidth||e.clientWidth||g.clientWidth,
height = w.innerHeight||e.clientHeight||g.clientHeight;

(https://www.bufa.es/vanilla-js-window-width-y-window-height/)

$(window).scrollTop()

Can be re-defined by:

const scrollTop =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

$(window).scroll

window.onscroll = () => {
  console.log('Scrolled');
};

$ajax()

The pollyfil is pretty complicated, but here it is

const $ajax = (() => {
  const that = {};
  that.send = (url, options) => {
    const on_success = options.onSuccess || function () {},
      on_error = options.onError || function () {},
      on_timeout = options.onTimeout || function () {},
      timeout = options.timeout || 10000;

    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = () => {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        try {
          var data = JSON.parse(xmlhttp.responseText);
        } catch (err) {
          console.error(`${err.message} in ${xmlhttp.responseText}`);
          return;
        }
        on_success(data);
      } else {
        if (xmlhttp.readyState == 4) {
          on_error();
        }
      }
    };
    xmlhttp.timeout = timeout;
    xmlhttp.ontimeout = () => {
      on_timeout();
    };
    xmlhttp.open('GET', url, true);
    xmlhttp.send();
  };
  return that;
})();

Example

$ajax.send('https://api.trnck.dev/', {
  onSuccess: (data) => {
    console.log('success', data);
  },
  onError: () => {
    console.log('Error');
  },
  onTimeout: () => {
    console.log('Timeout');
  },
  timeout: 10000,
});

A lot more: https://code.tutsplus.com/tutorials/from-jquery-to-javascript-a-reference--net-23703

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment