esedic
9/19/2016 - 7:02 PM

jQuery and vanilla Javascript alternative (ES2015)

jQuery and vanilla Javascript alternative (ES2015)

/* DOM: Selecting */

// jQuery
$('.user .user__name')

// JavaScript
document.querySelectorAll('.user .user__name');


/* DOM: Iterating with forEach */

// jQuery
$('.user').each(function () {
    console.log(this);
});

// JavaScript
let users = document.querySelectorAll('.user');
Array.from(users).forEach(function (user) {
    console.log(user);
});


/* DOM: Iterating with an iterator */

// jQuery
$('.user').each(function () {
    console.log(this);
});

// JavaScript
let users = document.querySelectorAll('.user');
for (let user of users) {
    console.log(user);
}


/* DOM: Selecting children */

// jQuery
$('.user').find('.user__tag');

// JavaScript
let users = document.querySelectorAll('.user');
let tags = [];

for (let user of users) {
    tags.push(...user.querySelectorAll('.user__tag'));
}


/* DOM: Selecting children */

// jQuery
$('.user').find('.user__tag');

// JavaScript
let users = document.querySelectorAll('.user');
let tags = [];

for (let user of users) {
    let tags = user.querySelectorAll('.user__tag');
    tags.push(tags[0], tags[1], ...);
}


/* DOM: .next() / .previous() / .parent() */

let $user = $('.user');
let user = document.querySelector('.user');

$user.next();
user.nextElementSibling;

$user.previous();
user.previousElementSibling;

$user.parent();
user.parentNode;
DOM: Attributes

$user.attr('aria-live');
user.getAttribute('aria-live');

$user.attr('aria-live', 'Your username is invalid');
user.setAttribute('aria-live', 'Your username is invalid');

// Data attributes have a special API
user.dataset.userName = 'Callum';
user.dataset.userName; // Callum


/* DOM: .html() / .text() / .val() */

let $user = $('.user');
let user = document.querySelector('.user');

$user.html();
user.innerHTML;

$user.text();
user.textContent; // Not innerText!

$('.some-input').val();
document.querySelector('.some-input').value;


/* DOM: Classes */

let $user = $('.user');
let user = document.querySelector('.user');

$user.addClass('user--admin');
user.classList.add('user--admin');

$user.removeClass('user--admin');
user.classList.remove('user--admin');

$user.toggleClass('user--admin');
user.classList.toggle('user--admin');

$user.hasClass('user--admin');
user.classList.contains('user--admin');


/* DOM: Styling */

let $user = $('.user');
let user = document.querySelector('user');

$user.css('background-color', 'orange');
user.style.backgroundColor = 'orange';

$user.css('background-color');
getComputedStyle(user).backgroundColor;


/* Event handling */

$('.user').on('click', function () {
    $(this).addClass('clicked');
});

let user = document.querySelector('user');
user.addEventListener('click', function () {
    user.classList.add('clicked');
});


/* Event handling */

$(document).on('click', '.user', function () {
    $(this).addClass('clicked');
});

document.addEventListener('click', function (e) {
    if (e.target.matches('.user')) {
        e.target.classList.add('clicked');
    }
});


/* Event handling */

$(document).on('click', '.user', function () {
    $(this).addClass('clicked');
});

function live(selector, event, cb) {
    document.addEventListener(event, function (e) {
        if (e.target.matches(selector)) {
            cb(e);
        }
    });
}

live('.user', 'click', function (e) {
    e.target.classList.add('clicked');
});


/* $.Deferred() */

var deferred = $.Deferred();

$('.yes').on('click', function () {
    deferred.resolve();
});

$('.no').on('click', function () {
    deferred.reject();
});

deferred
    .then(function () {
        console.log('success');
    })
    .fail(function () {
        console.log('fail');
    });


/* Promises */

var promise = new Promise(function (resolve, reject) {
    $('.yes').on('click', resolve);
    $('.no').on('click', reject);
});

promise
    .then(() => console.log('success'))
    .catch(() => console.log('fail'));


/* $.ajax() */

$.get('/api')
    .then(function (data) {
        console.log(data);
    })
    .catch(function (err) {
        console.error(err);
    });


/* XMLHttpRequest */

var request = new XMLHttpRequest();
request.open('GET', '/api');

request.onload = function () {
    var data = this.response;
    if (this.status >= 200 && this.status < 400) {
        console.log(data);
    } else {
        console.error(data);
    }
};

request.onerror = function (err) {
    console.error(err);
};

request.send();


/* Fetch */

fetch('/api')
    .then((res) => res.json());
    .then((data) => console.log(data))
    .catch((err) => console.error(err));

// GitHub polyfill for fetch(): https://github.com/github/fetch


/* Post form data */

// jQuery
$.post('/api', $('.my-form').serialize());

// JavaScript
let form = document.querySelector('.my-form');
fetch('/api', {
    method: 'post',
    body: new FormData(form)
});


/* Array helpers */

// Each
$.each(['a', 'b', 'c'], function (i, letter) {
    console.log(letter);
});

['a', 'b', 'c'].forEach(function (letter) {
    console.log(letter);
});

// Map
$.map(['a', 'b', 'c'], function (i, letter) {
    return letter.charCodeAt(0);
});

['a', 'b', 'c'].map(function (letter) {
    return letter.charCodeAt(0);
});


/* MORE array helpers */

// ECMAScript 5
Array.prototype.reduce()
Array.prototype.filter()
Array.prototype.every()
Array.prototype.some()

// ECMAScript 6
Array.from() // second argument!
Array.of()
Array.prototype.entries()
Array.prototype.keys()
Array.prototype.values()
Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.fill()


/* JSON */

$.parseJSON(data)


/* Merging objects */

// jQuery
function myPlugin(options) {
    options = $.extend({
        color: 'red',
        size: 3
    }, options);
}

// JavaScript
function myPlugin(options) {
    options = Object.assign({
        color: 'red',
        size: 3
    }, options);
}


/* Cloning objects */

$.extend({}, objectToClone);

Object.assign({}, objectToClone);