Skip to main content

Snippet from a great article that uses the JavaScript native/built-in Proxy object to chain together style manipulations changes on DOM elements.

/*
 * Chaining CSS Styles with a JavaScript Proxy
 *
 * Artcile: https://tobiasahlin.com/blog/chaining-styles-with-proxy/
 *
 * Example Usage:
 *
 * style(".menu")                 // Returns the style object in a Proxy
 *   .color("#fff")               // Updates color and returns a Proxy
 *   .backgroundColor("#000")     // Updates bgColor and returns a Proxy
 *   .opacity("1");               // ... and so on so forth
 *
 * style(".menu").color();        // Returns the current color ("#fff")
 * style(".menu").color("#000");  // Changes the color to black
 * style(".menu").color = "#fff"; // Changes the color back to "#fff" (white)
 *
 * More info on Proxy object at:
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
 */

// ES5 Version
// ---------------------------------------------------------------------------

"use strict";

var _styleProxy = {
    get: function(object, property) {
        return function(value) {
            if (value) {
                object[property] = value;
                return new Proxy(object, _styleProxy);
            }
            return object[property];
        };
    }
};

var style = function(selector) {
    var element = document.querySelector(selector);
    return new Proxy(element.style, _styleProxy);
};

// ES6 version
// ---------------------------------------------------------------------------

let _styleProxy = {
    get: (object, property) => {
        return value => {
            if (value) {
                object[property] = value;
                return new Proxy(object, _styleProxy);
            }
            return object[property];
        };
    }
};

let style = selector => {
    let element = document.querySelector(selector);
    return new Proxy(element.style, _styleProxy);
};