Skip to content
Snippets Groups Projects
ElementUpdate.js 2.42 KiB
/**
 * @author Rafael Ostertag <rafael.ostertag@math.uzh.ch>
 */

/* global $ */
/* global console */

/* @depend Utils.js */

var QfqNS = QfqNS || {};

(function (n) {
    'use strict';

    /**
     * Update HTML elements by a given id. Supports adding, setting, and removing attributes as well as setting the
     * text enclosed by the element.
     *
     * @type {{}}
     */
    n.ElementUpdate = {};


    /**
     * Update all elements according to configuration.
     *
     * @param config JSON configuration
     * @public
     */
    n.ElementUpdate.updateAll = function (config) {
        for (var idName in config) {
            if (!config.hasOwnProperty(idName)) {
                continue;
            }

            n.ElementUpdate.update(idName, config[idName]);
        }
    };

    /**
     *
     * @param elementId id of the element to update
     * @param config configuration
     */
    n.ElementUpdate.update = function (elementId, config) {
        var $element = n.ElementUpdate.$getElementById(elementId);

        if (config.attr) {
            n.ElementUpdate.handleAttributeUpdate($element, config.attr);
        }

        if (config.content) {
            n.ElementUpdate.setElementText($element, config.content);
        }

    };

    n.ElementUpdate.$getElementById = function (id) {
        return $("#" + n.escapeJqueryIdSelector(id));
    };

    n.ElementUpdate.handleAttributeUpdate = function ($element, attributes) {
        var attributeValue;
        for (var attributeName in attributes) {
            if (!attributes.hasOwnProperty(attributeName)) {
                continue;
            }

            attributeValue = attributes[attributeName];
            if (attributeValue === null) {
                n.ElementUpdate.deleteAttribute($element, attributeName);
            } else {
                n.ElementUpdate.setAttribute($element, attributeName, attributeValue);
            }
        }
    };

    n.ElementUpdate.setAttribute = function ($element, attributeName, attributeValue) {
        $element.attr(attributeName, attributeValue);
        if (attributeName.toLowerCase() === "value") {
            $element.val(attributeValue);
        }
    };

    n.ElementUpdate.deleteAttribute = function ($element, attributeName) {
        $element.removeAttr(attributeName);
    };

    n.ElementUpdate.setElementText = function ($element, text) {
        $element.empty().append($.parseHTML(text));
    };
})(QfqNS);