These notes are unpolished collections of thoughts, unfinished ideas, and things I want to remember later. In the spirit of learning in public, I'm sharing them here. Have fun exploring, if you want!

Replacing jQuery with Vanilla JavaScript

Tags: [[Drafts]] [[Code]] [[Javascript]]

Using for loops for binding event listeners

this.buttons = document.querySelectorAll('.media-item__play-button');
for (let i = 0; i < this.buttons.length; i++) {
const button = this.buttons[i];
button.addEventListener('click', () => {
// Do something
});
}

Adding and Removing Classes

const element = document.querySelector('.selector');
// Check if an element has a class
element.classList.contains('some-class');
// Add a class
element.classList.add('new-class');
// Remove a class
element.classList.remove('new-class');

Creating Elements and Appending Them

document.createElement

const self = e.currentTarget;
// Create the element.
const iframe = document.createElement('iframe');
// Add attributes.
iframe.src = videoService + videoId + videoSettings;
iframe.frameBorder = 0;
iframe.allowFullscreen = true;
// Append the element to somewhere else.
self.parentNode.appendChild(iframe);

Template Literals and innerHtml

function createMarkup(data) {
return `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
}
document.querySelector('.insert-here').innerHtml = createMarkup(data);

Scrolling

Scrolling the Page

window.scrollTo({
top: 100,
behavior: 'smooth'
});

Scroll an Element Into View

element.scrollIntoView({top: 0, behavior: 'smooth'});

Smooth Scroll Polyfill

Repo Demo

Figure out where an element is on the page.

const element = document.querySelector('.contact-us__form-wrapper');
// Scroll position plus element position minus height of fixed
// header plus some padding.
const top =
window.pageYOffset + element.getBoundingClientRect().top - 120;
// Scroll the window to the success message.
window.scroll({top: top, behavior: 'smooth'});

Get Parent / Get Closest

element.parentElement;

From Go Make Things

getClosest(elem, selector) {
// Element.matches() polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
const matches =
(this.document || this.ownerDocument).querySelectorAll(s);
let i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
for ( ; elem && elem !== document; elem = elem.parentNode ) {
if ( elem.matches( selector ) ) {
return elem;
}
}
return null;
}

Resources

© 2020 Ben Robertson

Proudly built with Gatsby.