summaryrefslogtreecommitdiffstats
path: root/public/js/helpers.js
blob: bcb2736298004e30433b88b49a715b2c3758e285 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*! Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

/* jQuery Plugins */
(function ($) {

    'use strict';

    /* Get data value or default */
    $.fn.getData = function (name, fallback) {
        var value = this.data(name);
        if (typeof value !== 'undefined') {
            return value;
        }

        return fallback;
    };

    /* Whether a HTML tag has a specific attribute */
    $.fn.hasAttr = function(name) {
        // We have inconsistent behaviour across browsers (false VS undef)
        var val = this.attr(name);
        return typeof val !== 'undefined' && val !== false;
    };

    /* Get class list */
    $.fn.classes = function (callback) {

        var classes = [];

        $.each(this, function (i, el) {
            var c = $(el).attr('class');
            if (typeof c === 'string') {
                $.each(c.split(/\s+/), function(i, p) {
                    if (classes.indexOf(p) === -1) {
                        classes.push(p);
                    }
                });
            }
        });

        if (typeof callback === 'function') {
            for (var i in classes) {
                if (classes.hasOwnProperty(i)) {
                    callback(classes[i]);
                }
            }
        }

        return classes;
    };

    /* Serialize form elements to an object */
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $.fn.offsetTopRelativeTo = function($ancestor) {
        if (typeof $ancestor === 'undefined') {
            return false;
        }

        var el = this[0];
        var offset = el.offsetTop;
        var $parent = $(el.offsetParent);

        if ($parent.is('body') || $parent.is($ancestor)) {
            return offset;
        }

        if (el.tagName === 'TR') {
            // TODO: Didn't found a better way, this will probably break sooner or later
            return $parent.offsetTopRelativeTo($ancestor);
        }

        return offset + $parent.offsetTopRelativeTo($ancestor);
    };

})(jQuery);