Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. /**
  2. * Pass in an element and its CSS Custom Property that you want the value of.
  3. * Optionally, you can determine what datatype you get back.
  4. *
  5. * @param {String} propKey
  6. * @param {HTMLELement} element=document.documentElement
  7. * @param {String} castAs='string'
  8. * @returns {*}
  9. */
  10. const getCSSCustomProp = (propKey, element = document.documentElement, castAs = 'string') => {
  11. let response = getComputedStyle(element).getPropertyValue(propKey);
  12.  
  13. // Tidy up the string if there's something to work with
  14. if (response.length) {
  15. response = response.replace(/\"/g, '').trim();
  16. }
  17.  
  18. // Convert the response into a whatever type we wanted
  19. switch (castAs) {
  20. case 'number':
  21. case 'int':
  22. return parseInt(response, 10);
  23. case 'float':
  24. return parseFloat(response, 10);
  25. case 'boolean':
  26. case 'bool':
  27. return response === 'true' || response === '1';
  28. }
  29.  
  30. // Return the string response by default
  31. return response;
  32. };
  33.  
  34. export default getCSSCustomProp;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement