Skip to content

Instantly share code, notes, and snippets.

@adamfaux85
Last active September 27, 2019 11:23
Show Gist options
  • Save adamfaux85/cfb1418d6b469dab589b2b1344193aca to your computer and use it in GitHub Desktop.
Save adamfaux85/cfb1418d6b469dab589b2b1344193aca to your computer and use it in GitHub Desktop.
Common JS commands
// Get Data Attribute
// ------------------------------------------------------------------------------------------
var elemData = elem.getAttribute('data-label');
// Remove from DOM
// ------------------------------------------------------------------------------------------
elemToDelete.parentNode.removeChild(elemToDelete);
// Set Background image
// ------------------------------------------------------------------------------------------
imageElem.style.backgroundImage = 'url("'+ imgURL +'")';
// Get all elements and attach click events to all.
// ------------------------------------------------------------------------------------------
var elems = document.querySelectorAll('.js--elem');
if( elems ) {
for (var i=0;i<elems.length;i++) {
elems[i].addEventListener('click', function(e) {
e.preventDefault();
console.log('action: click');
});
}
}
// Loop over array/objects
// ------------------------------------------------------------------------------------------
var elemArr = [];
elemArr.forEach(function (item, index) {
console.log(item);
});
// Set timeout
// ------------------------------------------------------------------------------------------
setTimeout(function(){
console.log('event: timer finished');
}, 800);
// Create new DOM Element, apply attributes, populate, append.
// ------------------------------------------------------------------------------------------
var newElem = document.createElement('div'),
newElemContent = null,
targetElem = null;
newElem.setAttribute('class', 'elem-class');
newElem.setAttribute('id', 'elem-id');
newElem.setAttribute('data-attr', 'some data');
newElemContent = '<span>';
newElemContent = 'This is the contents';
newElemContent = '</span>';
newElem.innerHTML += newElemContent;
targetElem.appendChild(newElem);
// Click elem event + off element click.
// ------------------------------------------------------------------------------------------
var bodyElem = document.querySelector('body'),
searchInput = document.querySelector('.js--search');
document.addEventListener('click', function (event) {
if (!event.target.matches('.js--search-trigger')) {
if( !event.target.parentNode.matches('.js--search-form') ) {
bodyElem.classList.remove('body--search-open');
}
return;
}
event.preventDefault();
if( bodyElem && searchInput ) {
bodyElem.classList.toggle('body--search-open');
searchInput.focus();
}
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment