From f31fba3d75136db72351f06e98387433d0e63be1 Mon Sep 17 00:00:00 2001 From: Anton Date: Tue, 13 Sep 2022 19:20:54 +0300 Subject: [PATCH] Add data renderer anchor --- dataRender/anchor.js | 77 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 dataRender/anchor.js diff --git a/dataRender/anchor.js b/dataRender/anchor.js new file mode 100644 index 0000000..58b7510 --- /dev/null +++ b/dataRender/anchor.js @@ -0,0 +1,77 @@ +/** + * @name anchor + * @summary Renders the column data as HTML anchor (`a` tag) + * @author [Fedonyuk Anton](http://ensostudio.ru) + * @requires DataTables 1.10+ + * + * @param {string} type The anchor type: 'link'(by default), 'phone' or 'email' + * @param {object|function} attributes The attributes of the anchor tag or the + * callback function returning the tag attributes, the callback syntax: + * `function (mixed data, object|array row[, object meta]): object` + * @param {string|null} innerText The inner text of the anchor tag or `null` to + * set text by column `data` (by default) + * @returns {string} + * + * @example + * // Display `...` + * $('#example').DataTable({ + * columnDefs: [{ + * targets: 1, + * render: $.fn.dataTable.render.anchor() + * }] + * }); + * + * @example + * // Display `...` + * $('#example').DataTable({ + * columnDefs: [{ + * targets: 2, + * render: $.fn.dataTable.render.anchor('email', {'class': 'link'}) + * }] + * }); + */ +jQuery.fn.dataTable.render.anchor = function ( + type = 'link', + attributes = {}, + innerText = null +) { + return function (data, type, row, meta) { + // restriction only for table display rendering + if (type !== 'display') { + return data; + } + + if (innerText === null) { + innerText = data; + } + + if (attributes typeof 'function') { + var tagAttributes = attributes(data, row, meta); + } else { + var tagAttributes = attributes; + } + + if (!tagAttributes.href) { + switch (type) { + case 'mail': + tagAttributes.href = 'mailto:' + data; + break; + case 'phone': + tagAttributes.href = 'tel:' + data.replace(/[^+\d]+/g, ''); + break; + case 'link': + case default: + try { + tagAttributes.href = new URL(data); + } catch (e) { + tagAttributes.href = data; + } + } + } + + var $a = jQuery(''); + $a.attr(tagAttributes).text(innerText === null ? data : innerText).get(0).outerText; + + return $a[0]; + }; +};