Skip to content

Instantly share code, notes, and snippets.

@jefBinomed
Created November 16, 2019 21:55
Show Gist options
  • Save jefBinomed/6d4e79bec71d365e8e0828c55ccbb925 to your computer and use it in GitHub Desktop.
Save jefBinomed/6d4e79bec71d365e8e0828c55ccbb925 to your computer and use it in GitHub Desktop.
Javascript class that helps you to play with Custom Properties to turn them into JS Code and to execute the code
export class HelperJsInCss{
constructor(element, customProperty, loop, args){
this.element = element
this.customProperty = customProperty
this.lastValue = undefined
this.loop = loop
this.args = args
if (loop){
window.requestAnimationFrame(this.checkElements.bind(this))
}else{
this.checkElements()
}
}
checkElements(){
const value = window.getComputedStyle(this.element).getPropertyValue(this.customProperty)
const computeArguments = []
if (this.args && this.args.length > 0){
this.args.forEach(argumentProperty => {
const argValue = window.getComputedStyle(this.element).getPropertyValue(argumentProperty)
computeArguments.push(argValue)
})
}
try{
const evaluateValue = eval(value)(...computeArguments)
if (this.lastValue === evaluateValue){
if (this.loop){
window.requestAnimationFrame(this.checkElements.bind(this))
}
return;
}
this.lastValue = evaluateValue
const computeName = `--compute${this.customProperty[2].toUpperCase()}${this.customProperty.substring(3)}`
this.element.style.setProperty(computeName, evaluateValue)
}catch(err){}
if (this.loop){
window.requestAnimationFrame(this.checkElements.bind(this))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment