Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Responsive BehaviourController Demo</h1>

<h2>Clock</h2>
<p>Clock will be active as long as the window is larger than 600 pixels.</p>
<div class="component">
    <div data-behaviour="Clock" data-conditions='{"window":{"minWidth":600}}'>Clock is inactive</div>
</div>

<h2>ClearField</h2>
<p>ClearField will be active as long as the window is smaller than 600 pixels.</p>
<div class="component">
    <input type="text" data-behaviour="ClearField"  data-conditions='{"window":{"maxWidth":600}}'>
</div>
              
            
!

CSS

              
                
html {
    background:#fff;
    line-height:1.5;
    padding:2em;
    color:#999;
    overflow:scroll;
}

html,input,textarea,button {
    font-family:Helvetica,Verdana,sans-serif;
    font-size:1em;
}

h1 {
    font-size:1.5em;
    color:#333;
}

h2 {
    margin-top:1.5em;
    font-size:1.25em;
    color:#333;
}

h2+p {
    margin-top:-.75em;
}

p {
    max-width:30em;
}

.component {
    padding:1em;
    border:1px dotted #ccc;
}
              
            
!

JS

              
                /*
 * Bind shim
 */
// bind method
if (Function.prototype.bind == null) {

    Function.prototype.bind = (function (slice){

        // (C) WebReflection - Mit Style License
        function bind(context) {

            var self = this; // "trapped" function reference

            // only if there is more than an argument
            // we are interested into more complex operations
            // this will speed up common bind creation
            // avoiding useless slices over arguments
            if (1 < arguments.length) {
                // extra arguments to send by default
                var $arguments = slice.call(arguments, 1);
                return function () {
                    return self.apply(
                        context,
                        // thanks @kangax for this suggestion
                        arguments.length ?
                            // concat arguments with those received
                            $arguments.concat(slice.call(arguments)) :
                            // send just arguments, no concat, no slice
                            $arguments
                    );
                };
            }
            // optimized callback
            return function () {
                // speed up when function is called without arguments
                return arguments.length ? self.apply(context, arguments) : self.call(context);
            };
        }

        // the named function
        return bind;

    }(Array.prototype.slice));

}


/*
 * Observer
 */
var Observer = {

    // subscribe to event
    subscribe:function(obj,type,fn) {

        if (!obj._listeners) {
            obj._listeners = new Array();
        }

        // check if already added
        var test,i,l = obj._listeners;
        for (i=0; i<l; i++) {
            test = obj._listeners[i];
            if (test.type === type && test.fn === fn) {
                return;
            }
        }

        // add event
        obj._listeners.push({'type':type,'fn':fn});
    },

    // unsubscribe from event
    unsubscribe:function() {

        if (!obj._listeners) {
            return;
        }

        // find and remove
        var test,i;
        for (i = obj._listeners.length-1; i >= 0; i--) {
            test = obj._listeners[i];
            if (test.type === type && test.fn === fn) {
                obj._listeners.splice(i,1);
                break;
            }
        }

    },

    // fire event
    fire:function(obj,type,data) {

        if (!obj._listeners) {
            obj._listeners = new Array();
        }

        // find and execute callback
        var test,i,l = obj._listeners.length;
        for (i=0; i<l; i++) {
            test = obj._listeners[i];
            if (test.type === type) {
                test.fn(data);
            }
        }
    }
};



/*
 * BehaviourBase Abstract Class
 */
var BehaviourBase = function(element) {
    this._element = element;
    this._element.setAttribute('data-initialized', 'true');
};

BehaviourBase.prototype._unload = function() {
    this._element.removeAttribute('data-initialized');
};



/*
 * Clock Class
 */
var Clock = function(element) {

    // Call BehaviourBase constructor
    BehaviourBase.call(this,element);

    // backup content
    this._inner = this._element.innerHTML;

    // start ticking
    this.tick();
};

// Extend from BehaviourBase
Clock.prototype = Object.create(BehaviourBase.prototype);

// Update time
Clock.prototype.tick = function() {
    this._element.textContent = new Date().toString();
    var self = this;
    this._timer = setTimeout(function(){
        self.tick();
    },1000);
};

// Unload Clock behaviour
Clock.prototype._unload = function() {

    // call BehaviourBase unload method
    BehaviourBase.prototype._unload.call(this);

    // stop ticking
    clearTimeout(this._timer);

    // restore content
    this._element.innerHTML = this._inner;
};



/*
 * ClearField Class
 */
var ClearField = function(element) {

    // Call BehaviourBase constructor
    BehaviourBase.call(this,element);

    // Add clear button
    var clearButton = document.createElement('button');
    clearButton.textContent = 'clear';
    clearButton.addEventListener('click',this);
    this._element.parentNode.insertBefore(clearButton,this._element);

};

// Extend from BehaviourBase
ClearField.prototype = Object.create(BehaviourBase.prototype);

// Handle events
ClearField.prototype.handleEvent = function(e) {
    if (e.type === 'click') {
        this._element.value = '';
    }
};

// Unload ClearField behaviour
ClearField.prototype._unload = function() {

    // call BehaviourBase unload method
    BehaviourBase.prototype._unload.call(this);

    // get button reference
    var clearButton = this._element.previousSibling;

    // remove events
    clearButton.removeEventListener('click',this);

    // remove clear button
    this._element.parentNode.removeChild(clearButton);
};



/*
 * BehaviourConditions Class
 */
var BehaviourConditions = function(element,properties) {

    // is the conditions are suitable, by default they are
    this._suitable = true;

    // set properties object
    this._properties = properties;

    // listen for environment changes
    this._listen();

    // test the conditions
    this._test();

};

// Static method construct creates behaviour condition objects
BehaviourConditions.construct = function(element) {

    // check if has specifications
    var specifications = element.getAttribute('data-conditions');
    if (!specifications) {
        return null;
    }

    var properties = null;
    try {
        properties = JSON.parse(specifications);
    }
    catch(e) {
        console.warn("BehaviourConditions: data-conditions attribute should have format data-conditions='{\"foo\":\"bar\"}'");
        return null;
    }

    return new BehaviourConditions(element,properties)

};

// Adds listeners to the environment to act when it changes
BehaviourConditions.prototype._listen = function() {

    if (this._properties.window) {
        window.addEventListener('resize',this);
    }

};

// Handles events
BehaviourConditions.prototype.handleEvent = function(e) {

    switch(e.type) {
        case 'resize':{
            this._test();
        }
            break;
        default: {}
            break;
    }

};

// Checks if the current conditions match the requested properties
BehaviourConditions.prototype._test = function() {

    // test condition properties
    var win,windowSize,suitable = true;

    // test window sizes
    if (win = this._properties.window) {

        // get window size
        windowSize = {x:window.innerWidth,y:window.innerHeight};

        // check max width
        if (win.maxWidth && windowSize.x > win.maxWidth) {
            suitable = false;
        }

        // check min width
        if (win.minWidth && windowSize.x < win.minWidth) {
            suitable = false;
        }

        // check max height
        if (win.maxHeight && windowSize.y > win.maxHeight) {
            suitable = false;
        }

        // check max height
        if (win.minHeight && windowSize.y < win.minHeight) {
            suitable = false;
        }

    }

    // fire changed event if condition suitability changed
    if (suitable != this._suitable) {
        this._suitable = suitable;
        Observer.fire(this,'change');
    }
};

// Returns the true if the current conditions are met
BehaviourConditions.prototype.areMet = function() {
    return this._suitable;
};



/*
 * BehaviourLoader Class
 */
var BehaviourLoader = function(element) {

    // set element reference
    this._element = element;

    // check if environment specified
    this._environment = BehaviourConditions.construct(this._element);
    if (!this._environment) {
        this._loadBehaviour();
    }
    else {

        // listen to changes in environment
        Observer.subscribe(this._environment,'change',this._onConditionsChange.bind(this));

        // if conditions are suitable, load my behaviour
        if (this._environment.areMet()) {
            this._loadBehaviour();
        }
    }

};

// Called when behaviour conditions change.
BehaviourLoader.prototype._onConditionsChange = function(e) {

    var suitable = this._environment.areMet();

    if (this._behaviour && !suitable) {
        this.unloadBehaviour();
    }

    if (!this._behaviour && suitable) {
        this._loadBehaviour();
    }
};

// Load the behaviour set in the data-behaviour attribute
BehaviourLoader.prototype._loadBehaviour = function() {

    var classPath = this._element.getAttribute('data-behaviour');

    this._behaviourConstructor = window[classPath];
    this._behaviour = new this._behaviourConstructor(this._element);
};

// Unload the behaviour
BehaviourLoader.prototype.unloadBehaviour = function() {

    if (!this._behaviour) {
        return false;
    }

    this._behaviour._unload();
    this._behaviour = null;

    return true;
};



/*
 * BehaviourController Static Class
 */
var BehaviourController = {

    applyDefault:function() {

        document.addEventListener('DOMContentLoaded',function(){
            BehaviourController.applyBehaviour(document);
        });

    },

    // Applies behaviour to given context
    applyBehaviour:function(context) {

        var behaviourConstructor,nodes,i,l;

        nodes = context.querySelectorAll('[data-behaviour]:not([data-processed])');
        l = nodes.length;

        for (i=0;i<l;i++) {

            // mark node as processed
            nodes[i].setAttribute('data-processed','true');

            // wrap in loader
            new BehaviourLoader(nodes[i]);

       }
    }

};



// Run
BehaviourController.applyDefault();
              
            
!
999px

Console