Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Last active August 29, 2015 14:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/144804438bf5bce8120a to your computer and use it in GitHub Desktop.
Save bloodyowl/144804438bf5bce8120a to your computer and use it in GitHub Desktop.
core
export function $(value) {
if(value == null) {
return []
}
if(typeof value === "string") {
return [...document.querySelectorAll(value)]
}
if(typeof value.nodeType === "number") {
return Array.of(value)
}
if(typeof value.length === "number") {
return [...value]
}
}
export function on(type, listener, capture) {
this.forEach((element) => {
element.addEventListener(type, listener, capture)
})
return this
}
export function off(type, listener, capture) {
this.forEach((element) => {
element.removeEventListener(type, listener, capture)
})
return this
}
export function addClass(...classNames) {
this.forEach((element) => {
element.classList.add(...classNames)
})
}
export function removeClass(...classNames) {
this.forEach((element) => {
element.classList.remove(...classNames)
})
return this
}
export function toggleClass(...classNames) {
this.forEach((element) => {
element.classList.toggle(...classNames)
})
return this
}
export function hasClass(...classNames) {
for(const element of this) {
return element.classList.contains(...classNames)
}
}
export function getStyle(propertyName) {
for(const element of this) {
return getComputedStyle(element, null)[propertyName]
}
}
export function setStyle(object) {
this.forEach((element) => {
for(let key in object) {
element.style[key] = object[key]
}
})
return this
}
export function getAttribute(attributeName) {
for(const element of this) {
return element.getAttribute(attributeName)
}
}
export function setAttribute(attributeName, value) {
this.forEach((element) => {
element.setAttribute(attributeName, value)
})
return this
}
export function hasAttribute(attributeName) {
for(const element of this) {
return element.hasAttribute(attributeName)
}
}
export function append(node) {
for(const element of this) {
if(!Array.isArray(node)) {
node = [node]
}
const fragment = document.createDocumentFragment()
node.forEach((node) => fragment.appendChild(node))
element.appendChild(fragment)
}
}
import {$, addEventListener, getStyle, setStyle} from "./core"
const node = $(document.createElement("div"))
$(document.body)
::append(node)
node
::setStyle({
"height": "100px",
"width": "100px",
"background-color": "#c30",
})
::on("click", () => {
node
::setStyle({
height: `${ parseInt(node::getStyle("height"), 10) + 100 }px`
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment