Created
November 16, 2019 21:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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