PrismJs line numbers for code blocks inside an expandable div appear wrapped. Recover when zoomed in/out - syntax-highlighting

I am trying to add line numbers to code blocks using PrismJs Line Numbers plugin.
The code blocks are included within an expanded div as shown below:
<h2><a class="dropspot" data-open-text="" data-rhwidget="ExpandSpot" data-target="expanding2" href="#">Sample </a></h2>
<div class="droptext" data-targetname="expanding2">
<p class="Codeheadingnew">Specify the inputs to create a job</p>
<div>
<pre class="line-numbers">
<code class="language-JSON">
{
"name": "Job with specific patches",
"description": "Created via API",
"approvches": [
"ca0d5b3a517",
"9285e676-61d84542c7bf"
],
</code>
</pre>
</div>
The CSS is here:
code[class*=language-],
pre[class*=language-] {
word-wrap: break-word;
color: #ccc;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 1em;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
background-color: #35434D;
max-height: 350px;
}
pre[class*=language-] {
padding: 1em;
margin-top: -0.1em;
margin-bottom: .5em;
overflow-y: auto;
scrollbar-width: thin;
white-space: pre-wrap;
}
:not(pre)>code[class*=language-],
pre[class*=language-] {
background: #35434D;
}
:not(pre)>code[class*=language-] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
/* Code style box scrollbar for Chrome and Edge */
pre[class*=language-]::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
border-radius: 0;
background-color: inherit;
}
pre[class*=language-]::-webkit-scrollbar {
width: 8px;
background-color: #F5F5F5;
}
pre[class*=language-]::-webkit-scrollbar-thumb {
border-radius: 0;
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
background-color: #898b8c;
}
.token.block-comment,
.token.cdata,
.token.comment,
.token.doctype,
.token.prolog {
color: #999;
}
.token.punctuation {
color: #ccc;
}
.token.attr-name,
.token.deleted,
.token.namespace,
.token.tag {
color: #e2777a;
}
.token.function-name {
color: #6196cc;
}
.token.boolean,
.token.function,
.token.number {
color: #f08d49;
}
.token.class-name,
.token.constant,
.token.property,
.token.symbol {
color: #f8c555;
}
.token.atrule,
.token.builtin,
.token.important,
.token.keyword,
.token.selector {
color: #cc99cd;
}
.token.attr-value,
.token.char,
.token.regex,
.token.string,
.token.variable {
color: #7ec699;
}
.token.entity,
.token.operator,
.token.url {
color: #67cdcc;
}
.token.bold,
.token.important {
font-weight: 700;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
.token.inserted {
color: green;
}
pre[class*=language-].line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre[class*=language-].line-numbers>code {
position: relative;
white-space: pre-wrap;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em;
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows>span {
display: block;
counter-increment: linenumber;
}
.line-numbers-rows>span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: .8em;
text-align: right;
}
and the JS is here:
var _self = "undefined" != typeof window ? window : "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope ? self : {}, Prism = function (e) { var n = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i, t = 0, r = {}, a = { manual: e.Prism && e.Prism.manual, disableWorkerMessageHandler: e.Prism && e.Prism.disableWorkerMessageHandler, util: { encode: function e(n) { return n instanceof i ? new i(n.type, e(n.content), n.alias) : Array.isArray(n) ? n.map(e) : n.replace(/&/g, "&").replace(/</g, "<").replace(/\u00a0/g, " ") }, type: function (e) { return Object.prototype.toString.call(e).slice(8, -1) }, objId: function (e) { return e.__id || Object.defineProperty(e, "__id", { value: ++t }), e.__id }, clone: function e(n, t) { var r, i; switch (t = t || {}, a.util.type(n)) { case "Object": if (i = a.util.objId(n), t[i]) return t[i]; for (var l in r = {}, t[i] = r, n) n.hasOwnProperty(l) && (r[l] = e(n[l], t)); return r; case "Array": return i = a.util.objId(n), t[i] ? t[i] : (r = [], t[i] = r, n.forEach((function (n, a) { r[a] = e(n, t) })), r); default: return n } }, getLanguage: function (e) { for (; e;) { var t = n.exec(e.className); if (t) return t[1].toLowerCase(); e = e.parentElement } return "none" }, setLanguage: function (e, t) { e.className = e.className.replace(RegExp(n, "gi"), ""), e.classList.add("language-" + t) }, currentScript: function () { if ("undefined" == typeof document) return null; if ("currentScript" in document) return document.currentScript; try { throw new Error } catch (r) { var e = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack) || [])[1]; if (e) { var n = document.getElementsByTagName("script"); for (var t in n) if (n[t].src == e) return n[t] } return null } }, isActive: function (e, n, t) { for (var r = "no-" + n; e;) { var a = e.classList; if (a.contains(n)) return !0; if (a.contains(r)) return !1; e = e.parentElement } return !!t } }, languages: { plain: r, plaintext: r, text: r, txt: r, extend: function (e, n) { var t = a.util.clone(a.languages[e]); for (var r in n) t[r] = n[r]; return t }, insertBefore: function (e, n, t, r) { var i = (r = r || a.languages)[e], l = {}; for (var o in i) if (i.hasOwnProperty(o)) { if (o == n) for (var s in t) t.hasOwnProperty(s) && (l[s] = t[s]); t.hasOwnProperty(o) || (l[o] = i[o]) } var u = r[e]; return r[e] = l, a.languages.DFS(a.languages, (function (n, t) { t === u && n != e && (this[n] = l) })), l }, DFS: function e(n, t, r, i) { i = i || {}; var l = a.util.objId; for (var o in n) if (n.hasOwnProperty(o)) { t.call(n, o, n[o], r || o); var s = n[o], u = a.util.type(s); "Object" !== u || i[l(s)] ? "Array" !== u || i[l(s)] || (i[l(s)] = !0, e(s, t, o, i)) : (i[l(s)] = !0, e(s, t, null, i)) } } }, plugins: {}, highlightAll: function (e, n) { a.highlightAllUnder(document, e, n) }, highlightAllUnder: function (e, n, t) { var r = { callback: t, container: e, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' }; a.hooks.run("before-highlightall", r), r.elements = Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)), a.hooks.run("before-all-elements-highlight", r); for (var i, l = 0; i = r.elements[l++];)a.highlightElement(i, !0 === n, r.callback) }, highlightElement: function (n, t, r) { var i = a.util.getLanguage(n), l = a.languages[i]; a.util.setLanguage(n, i); var o = n.parentElement; o && "pre" === o.nodeName.toLowerCase() && a.util.setLanguage(o, i); var s = { element: n, language: i, grammar: l, code: n.textContent }; function u(e) { s.highlightedCode = e, a.hooks.run("before-insert", s), s.element.innerHTML = s.highlightedCode, a.hooks.run("after-highlight", s), a.hooks.run("complete", s), r && r.call(s.element) } if (a.hooks.run("before-sanity-check", s), (o = s.element.parentElement) && "pre" === o.nodeName.toLowerCase() && !o.hasAttribute("tabindex") && o.setAttribute("tabindex", "0"), !s.code) return a.hooks.run("complete", s), void (r && r.call(s.element)); if (a.hooks.run("before-highlight", s), s.grammar) if (t && e.Worker) { var c = new Worker(a.filename); c.onmessage = function (e) { u(e.data) }, c.postMessage(JSON.stringify({ language: s.language, code: s.code, immediateClose: !0 })) } else u(a.highlight(s.code, s.grammar, s.language)); else u(a.util.encode(s.code)) }, highlight: function (e, n, t) { var r = { code: e, grammar: n, language: t }; if (a.hooks.run("before-tokenize", r), !r.grammar) throw new Error('The language "' + r.language + '" has no grammar.'); return r.tokens = a.tokenize(r.code, r.grammar), a.hooks.run("after-tokenize", r), i.stringify(a.util.encode(r.tokens), r.language) }, tokenize: function (e, n) { var t = n.rest; if (t) { for (var r in t) n[r] = t[r]; delete n.rest } var a = new s; return u(a, a.head, e), o(e, a, n, a.head, 0), function (e) { for (var n = [], t = e.head.next; t !== e.tail;)n.push(t.value), t = t.next; return n }(a) }, hooks: { all: {}, add: function (e, n) { var t = a.hooks.all; t[e] = t[e] || [], t[e].push(n) }, run: function (e, n) { var t = a.hooks.all[e]; if (t && t.length) for (var r, i = 0; r = t[i++];)r(n) } }, Token: i }; function i(e, n, t, r) { this.type = e, this.content = n, this.alias = t, this.length = 0 | (r || "").length } function l(e, n, t, r) { e.lastIndex = n; var a = e.exec(t); if (a && r && a[1]) { var i = a[1].length; a.index += i, a[0] = a[0].slice(i) } return a } function o(e, n, t, r, s, g) { for (var f in t) if (t.hasOwnProperty(f) && t[f]) { var h = t[f]; h = Array.isArray(h) ? h : [h]; for (var d = 0; d < h.length; ++d) { if (g && g.cause == f + "," + d) return; var v = h[d], p = v.inside, m = !!v.lookbehind, y = !!v.greedy, k = v.alias; if (y && !v.pattern.global) { var x = v.pattern.toString().match(/[imsuy]*$/)[0]; v.pattern = RegExp(v.pattern.source, x + "g") } for (var b = v.pattern || v, w = r.next, A = s; w !== n.tail && !(g && A >= g.reach); A += w.value.length, w = w.next) { var E = w.value; if (n.length > e.length) return; if (!(E instanceof i)) { var P, L = 1; if (y) { if (!(P = l(b, A, e, m)) || P.index >= e.length) break; var S = P.index, O = P.index + P[0].length, j = A; for (j += w.value.length; S >= j;)j += (w = w.next).value.length; if (A = j -= w.value.length, w.value instanceof i) continue; for (var C = w; C !== n.tail && (j < O || "string" == typeof C.value); C = C.next)L++, j += C.value.length; L--, E = e.slice(A, j), P.index -= A } else if (!(P = l(b, 0, E, m))) continue; S = P.index; var N = P[0], _ = E.slice(0, S), M = E.slice(S + N.length), W = A + E.length; g && W > g.reach && (g.reach = W); var z = w.prev; if (_ && (z = u(n, z, _), A += _.length), c(n, z, L), w = u(n, z, new i(f, p ? a.tokenize(N, p) : N, k, N)), M && u(n, w, M), L > 1) { var I = { cause: f + "," + d, reach: W }; o(e, n, t, w.prev, A, I), g && I.reach > g.reach && (g.reach = I.reach) } } } } } } function s() { var e = { value: null, prev: null, next: null }, n = { value: null, prev: e, next: null }; e.next = n, this.head = e, this.tail = n, this.length = 0 } function u(e, n, t) { var r = n.next, a = { value: t, prev: n, next: r }; return n.next = a, r.prev = a, e.length++, a } function c(e, n, t) { for (var r = n.next, a = 0; a < t && r !== e.tail; a++)r = r.next; n.next = r, r.prev = n, e.length -= a } if (e.Prism = a, i.stringify = function e(n, t) { if ("string" == typeof n) return n; if (Array.isArray(n)) { var r = ""; return n.forEach((function (n) { r += e(n, t) })), r } var i = { type: n.type, content: e(n.content, t), tag: "span", classes: ["token", n.type], attributes: {}, language: t }, l = n.alias; l && (Array.isArray(l) ? Array.prototype.push.apply(i.classes, l) : i.classes.push(l)), a.hooks.run("wrap", i); var o = ""; for (var s in i.attributes) o += " " + s + '="' + (i.attributes[s] || "").replace(/"/g, """) + '"'; return "<" + i.tag + ' class="' + i.classes.join(" ") + '"' + o + ">" + i.content + "</" + i.tag + ">" }, !e.document) return e.addEventListener ? (a.disableWorkerMessageHandler || e.addEventListener("message", (function (n) { var t = JSON.parse(n.data), r = t.language, i = t.code, l = t.immediateClose; e.postMessage(a.highlight(i, a.languages[r], r)), l && e.close() }), !1), a) : a; var g = a.util.currentScript(); function f() { a.manual || a.highlightAll() } if (g && (a.filename = g.src, g.hasAttribute("data-manual") && (a.manual = !0)), !a.manual) { var h = document.readyState; "loading" === h || "interactive" === h && g && g.defer ? document.addEventListener("DOMContentLoaded", f) : window.requestAnimationFrame ? window.requestAnimationFrame(f) : window.setTimeout(f, 16) } return a }(_self); "undefined" != typeof module && module.exports && (module.exports = Prism), "undefined" != typeof global && (global.Prism = Prism);
Prism.languages.json = { property: { pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/, lookbehind: !0, greedy: !0 }, string: { pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/, lookbehind: !0, greedy: !0 }, comment: { pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/, greedy: !0 }, number: /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i, punctuation: /[{}[\],]/, operator: /:/, boolean: /\b(?:false|true)\b/, null: { pattern: /\bnull\b/, alias: "keyword" } }, Prism.languages.webmanifest = Prism.languages.json;
!function (n) { var e = /("|')(?:\\(?:\r\n?|\n|.)|(?!\1)[^\\\r\n])*\1/; n.languages.json5 = n.languages.extend("json", { property: [{ pattern: RegExp(e.source + "(?=\\s*:)"), greedy: !0 }, { pattern: /(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/, alias: "unquoted" }], string: { pattern: e, greedy: !0 }, number: /[+-]?\b(?:NaN|Infinity|0x[a-fA-F\d]+)\b|[+-]?(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[eE][+-]?\d+\b)?/ }) }(Prism);
Prism.languages.jsonp = Prism.languages.extend("json", { punctuation: /[{}[\]();,.]/ }), Prism.languages.insertBefore("jsonp", "punctuation", { function: /(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*\()/ });
!function () { if ("undefined" != typeof Prism && "undefined" != typeof document) { var e = "line-numbers", n = /\n(?!$)/g, t = Prism.plugins.lineNumbers = { getLine: function (n, t) { if ("PRE" === n.tagName && n.classList.contains(e)) { var i = n.querySelector(".line-numbers-rows"); if (i) { var r = parseInt(n.getAttribute("data-start"), 10) || 1, s = r + (i.children.length - 1); t < r && (t = r), t > s && (t = s); var l = t - r; return i.children[l] } } }, resize: function (e) { r([e]) }, assumeViewportIndependence: !0 }, i = void 0; window.addEventListener("resize", (function () { t.assumeViewportIndependence && i === window.innerWidth || (i = window.innerWidth, r(Array.prototype.slice.call(document.querySelectorAll("pre.line-numbers")))) })), Prism.hooks.add("complete", (function (t) { if (t.code) { var i = t.element, s = i.parentNode; if (s && /pre/i.test(s.nodeName) && !i.querySelector(".line-numbers-rows") && Prism.util.isActive(i, e)) { i.classList.remove(e), s.classList.add(e); var l, o = t.code.match(n), a = o ? o.length + 1 : 1, u = new Array(a + 1).join("<span></span>"); (l = document.createElement("span")).setAttribute("aria-hidden", "true"), l.className = "line-numbers-rows", l.innerHTML = u, s.hasAttribute("data-start") && (s.style.counterReset = "linenumber " + (parseInt(s.getAttribute("data-start"), 10) - 1)), t.element.appendChild(l), r([s]), Prism.hooks.run("line-numbers", t) } } })), Prism.hooks.add("line-numbers", (function (e) { e.plugins = e.plugins || {}, e.plugins.lineNumbers = !0 })) } function r(e) { if (0 != (e = e.filter((function (e) { var n, t = (n = e, n ? window.getComputedStyle ? getComputedStyle(n) : n.currentStyle || null : null)["white-space"]; return "pre-wrap" === t || "pre-line" === t }))).length) { var t = e.map((function (e) { var t = e.querySelector("code"), i = e.querySelector(".line-numbers-rows"); if (t && i) { var r = e.querySelector(".line-numbers-sizer"), s = t.textContent.split(n); r || ((r = document.createElement("span")).className = "line-numbers-sizer", t.appendChild(r)), r.innerHTML = "0", r.style.display = "block"; var l = r.getBoundingClientRect().height; return r.innerHTML = "", { element: e, lines: s, lineHeights: [], oneLinerHeight: l, sizer: r } } })).filter(Boolean); t.forEach((function (e) { var n = e.sizer, t = e.lines, i = e.lineHeights, r = e.oneLinerHeight; i[t.length - 1] = void 0, t.forEach((function (e, t) { if (e && e.length > 1) { var s = n.appendChild(document.createElement("span")); s.style.display = "block", s.textContent = e } else i[t] = r })) })), t.forEach((function (e) { for (var n = e.sizer, t = e.lineHeights, i = 0, r = 0; r < t.length; r++)void 0 === t[r] && (t[r] = n.children[i++].getBoundingClientRect().height) })), t.forEach((function (e) { var n = e.sizer, t = e.element.querySelector(".line-numbers-rows"); n.style.display = "none", n.innerHTML = "", e.lineHeights.forEach((function (e, n) { t.children[n].style.height = e + "px" })) })) } } }();
!function () { if ("undefined" != typeof Prism) { var e = Object.assign || function (e, t) { for (var n in t) t.hasOwnProperty(n) && (e[n] = t[n]); return e }, t = { "remove-trailing": "boolean", "remove-indent": "boolean", "left-trim": "boolean", "right-trim": "boolean", "break-lines": "number", indent: "number", "remove-initial-line-feed": "boolean", "tabs-to-spaces": "number", "spaces-to-tabs": "number" }; n.prototype = { setDefaults: function (t) { this.defaults = e(this.defaults, t) }, normalize: function (t, n) { for (var r in n = e(this.defaults, n)) { var i = r.replace(/-(\w)/g, (function (e, t) { return t.toUpperCase() })); "normalize" !== r && "setDefaults" !== i && n[r] && this[i] && (t = this[i].call(this, t, n[r])) } return t }, leftTrim: function (e) { return e.replace(/^\s+/, "") }, rightTrim: function (e) { return e.replace(/\s+$/, "") }, tabsToSpaces: function (e, t) { return t = 0 | t || 4, e.replace(/\t/g, new Array(++t).join(" ")) }, spacesToTabs: function (e, t) { return t = 0 | t || 4, e.replace(RegExp(" {" + t + "}", "g"), "\t") }, removeTrailing: function (e) { return e.replace(/\s*?$/gm, "") }, removeInitialLineFeed: function (e) { return e.replace(/^(?:\r?\n|\r)/, "") }, removeIndent: function (e) { var t = e.match(/^[^\S\n\r]*(?=\S)/gm); return t && t[0].length ? (t.sort((function (e, t) { return e.length - t.length })), t[0].length ? e.replace(RegExp("^" + t[0], "gm"), "") : e) : e }, indent: function (e, t) { return e.replace(/^[^\S\n\r]*(?=\S)/gm, new Array(++t).join("\t") + "$&") }, breakLines: function (e, t) { t = !0 === t ? 80 : 0 | t || 80; for (var n = e.split("\n"), i = 0; i < n.length; ++i)if (!(r(n[i]) <= t)) { for (var o = n[i].split(/(\s+)/g), a = 0, l = 0; l < o.length; ++l) { var s = r(o[l]); (a += s) > t && (o[l] = "\n" + o[l], a = s) } n[i] = o.join("") } return n.join("\n") } }, "undefined" != typeof module && module.exports && (module.exports = n), Prism.plugins.NormalizeWhitespace = new n({ "remove-trailing": !0, "remove-indent": !0, "left-trim": !0, "right-trim": !0 }), Prism.hooks.add("before-sanity-check", (function (e) { var n = Prism.plugins.NormalizeWhitespace; if ((!e.settings || !1 !== e.settings["whitespace-normalization"]) && Prism.util.isActive(e.element, "whitespace-normalization", !0)) if (e.element && e.element.parentNode || !e.code) { var r = e.element.parentNode; if (e.code && r && "pre" === r.nodeName.toLowerCase()) { for (var i in null == e.settings && (e.settings = {}), t) if (Object.hasOwnProperty.call(t, i)) { var o = t[i]; if (r.hasAttribute("data-" + i)) try { var a = JSON.parse(r.getAttribute("data-" + i) || "true"); typeof a === o && (e.settings[i] = a) } catch (e) { } } for (var l = r.childNodes, s = "", c = "", u = !1, m = 0; m < l.length; ++m) { var f = l[m]; f == e.element ? u = !0 : "#text" === f.nodeName && (u ? c += f.nodeValue : s += f.nodeValue, r.removeChild(f), --m) } if (e.element.children.length && Prism.plugins.KeepMarkup) { var d = s + e.element.innerHTML + c; e.element.innerHTML = n.normalize(d, e.settings), e.code = e.element.textContent } else e.code = s + e.code + c, e.code = n.normalize(e.code, e.settings) } } else e.code = n.normalize(e.code, e.settings) })) } function n(t) { this.defaults = e({}, t) } function r(e) { for (var t = 0, n = 0; n < e.length; ++n)e.charCodeAt(n) == "\t".charCodeAt(0) && (t += 3); return e.length + t } }();
!function () { if ("undefined" != typeof Prism && "undefined" != typeof document) { var e = [], t = {}, n = function () { }; Prism.plugins.toolbar = {}; var a = Prism.plugins.toolbar.registerButton = function (n, a) { var r; r = "function" == typeof a ? a : function (e) { var t; return "function" == typeof a.onClick ? ((t = document.createElement("button")).type = "button", t.addEventListener("click", (function () { a.onClick.call(this, e) }))) : "string" == typeof a.url ? (t = document.createElement("a")).href = a.url : t = document.createElement("span"), a.className && t.classList.add(a.className), t.textContent = a.text, t }, n in t ? console.warn('There is a button with the key "' + n + '" registered already.') : e.push(t[n] = r) }, r = Prism.plugins.toolbar.hook = function (a) { var r = a.element.parentNode; if (r && /pre/i.test(r.nodeName) && !r.parentNode.classList.contains("code-toolbar")) { var o = document.createElement("div"); o.classList.add("code-toolbar"), r.parentNode.insertBefore(o, r), o.appendChild(r); var i = document.createElement("div"); i.classList.add("toolbar"); var l = e, d = function (e) { for (; e;) { var t = e.getAttribute("data-toolbar-order"); if (null != t) return (t = t.trim()).length ? t.split(/\s*,\s*/g) : []; e = e.parentElement } }(a.element); d && (l = d.map((function (e) { return t[e] || n }))), l.forEach((function (e) { var t = e(a); if (t) { var n = document.createElement("div"); n.classList.add("toolbar-item"), n.appendChild(t), i.appendChild(n) } })), o.appendChild(i) } }; a("label", (function (e) { var t = e.element.parentNode; if (t && /pre/i.test(t.nodeName) && t.hasAttribute("data-label")) { var n, a, r = t.getAttribute("data-label"); try { a = document.querySelector("template#" + r) } catch (e) { } return a ? n = a.content : (t.hasAttribute("data-url") ? (n = document.createElement("a")).href = t.getAttribute("data-url") : n = document.createElement("span"), n.textContent = r), n } })), Prism.hooks.add("complete", r) } }();
!function () { function t(t) { var e = document.createElement("textarea"); e.value = t.getText(), e.style.top = "0", e.style.left = "0", e.style.position = "fixed", document.body.appendChild(e), e.focus(), e.select(); try { var o = document.execCommand("copy"); setTimeout((function () { o ? t.success() : t.error() }), 1) } catch (e) { setTimeout((function () { t.error(e) }), 1) } document.body.removeChild(e) } "undefined" != typeof Prism && "undefined" != typeof document && (Prism.plugins.toolbar ? Prism.plugins.toolbar.registerButton("copy-to-clipboard", (function (e) { var o = e.element, n = function (t) { var e = { copy: "Copy", "copy-error": "Press Ctrl+C to copy", "copy-success": "Copied!", "copy-timeout": 5e3 }; for (var o in e) { for (var n = "data-Prismjs-" + o, c = t; c && !c.hasAttribute(n);)c = c.parentElement; c && (e[o] = c.getAttribute(n)) } return e }(o), c = document.createElement("button"); c.className = "copy-to-clipboard-button", c.setAttribute("type", "button"); var r = document.createElement("span"); return c.appendChild(r), u("copy"), function (e, o) { e.addEventListener("click", (function () { !function (e) { navigator.clipboard ? navigator.clipboard.writeText(e.getText()).then(e.success, (function () { t(e) })) : t(e) }(o) })) }(c, { getText: function () { return o.textContent }, success: function () { u("copy-success"), i() }, error: function () { u("copy-error"), setTimeout((function () { !function (t) { window.getSelection().selectAllChildren(t) }(o) }), 1), i() } }), c; function i() { setTimeout((function () { u("copy") }), n["copy-timeout"]) } function u(t) { r.textContent = n[t], c.setAttribute("data-copy-state", t) } })) : console.warn("Copy to Clipboard plugin loaded before Toolbar plugin.")) }();
When published the line numbers appear wrapped into a single number as shown below:
Line numbers appear wrapped up
When zooming in or out, the line numbers appear good.
Line numbers appear ok when zooming in or out
When the same code block is added outside the expander, the line numbers appear correctly.
What could be the issue?

Related

Error when selecting row in DataTable after generate table for the second time

Try to create multiple selection table with DataTable. But the problem is, if the table is recreated multiple times. It shows error Cannot read properties of undefined (reading '_DTTT_selected') when select row table . But it's working properly on the first table generate
Here's my JS code
Error is shown when selecting row after run getTable function for the second time
function getTable(){
$("#tblDisbursement").DataTable().clear();
$("#tblDisbursement").DataTable().destroy();
var a = generateDatatables();
}
function generateDatatables() {
$.ajax({
type: "POST",
url: "${local_server}/controller/gettableFilter",
data: $("#formDDL").serialize(),
async:true,
beforeSend : function(){
showLoadingProg(true,"load data");
},
success: function(e) {
showLoadingProg(false);
console.log("ini e");
console.log(e);
if(e.status!="Success"){
$.alert("Error/ Failed");
}
console.log("oini t");
var n = [];
var a = 0;
$.each(e.data, function(e, t) {
var c = new Object;
$.each(t.loan, function(e, t) {
c.loan_acc_no = null != t.loan_acc_no ? t.loan_acc_no : "", c.loan_cif = null != t.loan_cif ? t.loan_cif : "", c.fullname = null != t.fullname ? t.fullname : "", c.loan_prd_code = null != t.loan_prd_code ? t.loan_prd_code : "", c.loan_disb_amount_needs = null != t.loan_disb_amount_needs ? t.loan_disb_amount_needs : "", c.ldi_req_date = null != t.ldi_req_date ? t.ldi_req_date : "", c.status = null != t.status ? t.status : ""
}), n[a] = c, a++
})
var e= $("#tblDisbursement").DataTable({
data: n,
order: [
[5, 'desc']
],
lengthMenu: [
[10, 25, 50, 100, 200, 300, -1],
[10, 25, 50, 100, 200, 300, "All"]
],
columns: [{
render: function(e, t, n) {
return '<input type="checkbox" class="cekbox" name="acc[]" value="' + n.loan_acc_no + '">'
},
orderable: !1
}, {
data: "loan_acc_no"
}, {
data: "fullname",
}, {
data: "loan_prd_code",
render: function(e, t, n) {
var a = "";
return String(n.loan_prd_code).includes("A06") ? "KiniGajian" : "";
}
}, {
data: "loan_disb_amount_needs",
// className: "txtRigth",
render: function(e, t, n) {
return toRp(n.loan_disb_amount_needs)
}
}, {
data: "ldi_req_date",
render: function(e, t, n) {
return null != e ? n.ldi_req_date.replace("T", " ") : ""
}
}, {
data: "status"
} /* {
render: function(e, t, n) {
var a = "";
var x = (n.cga_nik != "Public")?n.cga_nik:n.loan_cif;
// console.log(n.cga_filename);
return a = null != n.cga_filename ? "<span class="label label-success">Image</span>' : '<span class="label label-default">No Image</span>'
}
}, */
/*{
render: function(e, t, n) {
var a = '<button class="edit btn btn-xs btn-success" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-edit"></i></button>';
return a += '<button class="view btn btn-xs btn-info" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-eye"></i></button>'
},
orderable: !1
}*/
]
});
var t = new $.fn.dataTable.TableTools(e, {
sSwfPath: "",
sRowSelector: "td:not(:last-child)",
sRowSelect: "multi",
fnRowSelected: function(e) {
console.log(e);
try {
$(e).find("input[type=checkbox]").get(0).checked = !0;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), t == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0), 0 != n && $("#btn-dis-all").removeClass("disabled")
} catch (a) {}
},
fnRowDeselected: function(e) {
try {
console..log(e);
$(e).find("input[type=checkbox]").get(0).checked = !1;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), 0 == n && $("#btn-dis-all").addClass("disabled"), t == n && 1 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !1)
} catch (a) {}
},
sSelectedClass: "success"
});
$("#tblDisbursement > thead > tr > td input[type=checkbox]").eq(0).on("click", function() {
var e = this.checked,
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), $(this).closest("table").find("tbody > tr").each(function() {
var a = this;
e ? (t.fnSelect(a), $("#btn-dis-all").removeClass("disabled")) : (t.fnDeselect(a), n >= 1 && $("#btn-dis-all").addClass("disabled"))
})
}),
$("#tblDisbursement").on("click", "tr td input[type=checkbox]", function() {
var e = $(this).closest("tr").get(0),
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
});
var a = -1;
$.each($(".cekbox"), function(e, t) {
a++
}), this.checked ? (t.fnSelect(e), n > 0 && $("#btn-dis-all").removeClass("disabled"), a == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0)) : (t.fnDeselect(e), n > 0 && 1 == document.getElementById("cek").checked && 1 == n && (document.getElementById("cek").checked = !1, $("#btn-dis-all").addClass("disabled")))
})
}

How to fixed the header of the table in the page?

This is my view page:
In this page when the scroll the entire page in chrome the header of the table should be fixed only content should be scrolled.I have searched many codes in google but it not working.
My table code:
<table id="customers" >
<thead>
<tr>
<th>MillCode</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($query as $row): ?>
<tr>
<td><a href="<?=site_url('Sales/Sales_Edit/'.$row['millcode'])?>"><?=$row['mname']?></td>
<td dir="rtl"><a href="<?=site_url('Sales/Sales_Edit/'.$row['millcode'])?>"><?php echo number_format($row['amount']);?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
Please help to solve this problem.
Wrap your table under a div <div class="table-wrapper"></div> and apply this css.
div.table-wrapper {
border: 1px solid #ccc;
height: 100px;
width: 100%;
overflow-y: auto;
}
table,thead,tr,th {
text-align: left;
position: sticky;
top: 0px;
background-color: #666;
color: #fff;
}
try this
HTML:
<table class="fixed-header" border="1">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1.0</td>
<td>Row 1.1</td>
<td>Row 1.2</td>
<td>Row 1.3</td>
<td>Row 1.4</td>
</tr>
<tr>
<td>Row 2.0</td>
<td>Row 2.1</td>
<td>Row 2.2</td>
<td>Row 2.3</td>
<td>Row 2.4</td>
</tr>
<tr>
<td>Row 3.0</td>
<td>Row 3.1</td>
<td>Row 3.2</td>
<td>Row 3.3</td>
<td>Row 3.4</td>
</tr>
<tr>
<td>Row 4.0</td>
<td>Row 4.1</td>
<td>Row 4.2</td>
<td>Row 4.3</td>
<td>Row 4.4</td>
</tr>
<tr>
<td>Row 5.0</td>
<td>Row 5.1</td>
<td>Row 5.2</td>
<td>Row 5.3</td>
<td>Row 5.4</td>
</tr>
<tr>
<td>Row 6.0</td>
<td>Row 6.1</td>
<td>Row 6.2</td>
<td>Row 6.3</td>
<td>Row 6.4</td>
</tr>
<tr>
<td>Row 7.0</td>
<td>Row 7.1</td>
<td>Row 7.2</td>
<td>Row 7.3</td>
<td>Row 7.4</td>
</tr>
</tbody>
</table>
CSS:
.fixed-header{
width: 400px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed-header tbody{
display:block;
width: 100%;
overflow: auto;
height: 100px;
}
.fixed-header thead tr {
display: block;
}
.fixed-header th, .fixed-header td {
padding: 5px;
text-align: left;
width: 200px;
}
find the demo: https://jsfiddle.net/tzk9d5s7/1/
You can stick header using javaScript
**HTML**
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Sticky Table Headers</h1>
</div>
<table class="table table-striped sticky-header">
<thead>
<tr>
<th>#</th>
<th>New Table</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
CSS
body {
padding-top:50px;
}
table.floatThead-table {
border-top: none;
border-bottom: none;
background-color: #fff;
}
JS
// #preserve jQuery.floatThead 1.2.9 - http://mkoryak.github.io/floatThead/ - Copyright (c) 2012 - 2014 Misha Koryak
// #license MIT
! function (a) {
function b(a, b, c) {
if (8 == g) {
var d = j.width(),
e = f.debounce(function () {
var a = j.width();
d != a && (d = a, c())
}, a);
j.on(b, e)
} else j.on(b, f.debounce(c, a))
}
function c(a) {
window.console && window.console && window.console.log && window.console.log(a)
}
function d() {
var b = a('<div style="width:50px;height:50px;overflow-y:scroll;position:absolute;top:-200px;left:-200px;"><div style="height:100px;width:100%"></div>');
a("body").append(b);
var c = b.innerWidth(),
d = a("div", b).innerWidth();
return b.remove(), c - d
}
function e(a) {
if (a.dataTableSettings) for (var b = 0; b < a.dataTableSettings.length; b++) {
var c = a.dataTableSettings[b].nTable;
if (a[0] == c) return !0
}
return !1
}
a.floatThead = a.floatThead || {}, a.floatThead.defaults = {
cellTag: null,
headerCellSelector: "tr:first>th:visible",
zIndex: 1001,
debounceResizeMs: 10,
useAbsolutePositioning: !0,
scrollingTop: 0,
scrollingBottom: 0,
scrollContainer: function () {
return a([])
},
getSizingRow: function (a) {
return a.find("tbody tr:visible:first>*")
},
floatTableClass: "floatThead-table",
floatWrapperClass: "floatThead-wrapper",
floatContainerClass: "floatThead-container",
copyTableClass: !0,
debug: !1
};
var f = window._,
g = function () {
for (var a = 3, b = document.createElement("b"), c = b.all || []; a = 1 + a, b.innerHTML = "<\!--[if gt IE " + a + "]><i><![endif]-->", c[0];);
return a > 4 ? a : document.documentMode
}(),
h = null,
i = function () {
if (g) return !1;
var b = a("<table><colgroup><col></colgroup><tbody><tr><td style='width:10px'></td></tbody></table>");
a("body").append(b);
var c = b.find("col").width();
return b.remove(), 0 == c
}, j = a(window),
k = 0;
a.fn.floatThead = function (l) {
if (l = l || {}, !f && (f = window._ || a.floatThead._, !f)) throw new Error("jquery.floatThead-slim.js requires underscore. You should use the non-lite version since you do not have underscore.");
if (8 > g) return this;
if (null == h && (h = i(), h && (document.createElement("fthtr"), document.createElement("fthtd"), document.createElement("fthfoot"))), f.isString(l)) {
var m = l,
n = this;
return this.filter("table").each(function () {
var b = a(this).data("floatThead-attached");
if (b && f.isFunction(b[m])) {
var c = b[m]();
"undefined" != typeof c && (n = c)
}
}), n
}
var o = a.extend({}, a.floatThead.defaults || {}, l);
return a.each(l, function (b) {
b in a.floatThead.defaults || !o.debug || c("jQuery.floatThead: used [" + b + "] key to init plugin, but that param is not an option for the plugin. Valid options are: " + f.keys(a.floatThead.defaults).join(", "))
}), this.filter(":not(." + o.floatTableClass + ")").each(function () {
function c(a) {
return a + ".fth-" + y + ".floatTHead"
}
function i() {
var b = 0;
A.find("tr:visible").each(function () {
b += a(this).outerHeight(!0)
}), Z.outerHeight(b), $.outerHeight(b)
}
function l() {
var a = z.outerWidth(),
b = I.width() || a;
if (X.width(b - F.vertical), O) {
var c = 100 * a / (b - F.vertical);
S.css("width", c + "%")
} else S.outerWidth(a)
}
function m() {
C = (f.isFunction(o.scrollingTop) ? o.scrollingTop(z) : o.scrollingTop) || 0, D = (f.isFunction(o.scrollingBottom) ? o.scrollingBottom(z) : o.scrollingBottom) || 0
}
function n() {
var b, c;
if (V) b = U.find("col").length;
else {
var d;
d = null == o.cellTag && o.headerCellSelector ? o.headerCellSelector : "tr:first>" + o.cellTag, c = A.find(d), b = 0, c.each(function () {
b += parseInt(a(this).attr("colspan") || 1, 10)
})
}
if (b != H) {
H = b;
for (var e = [], f = [], g = [], i = 0; b > i; i++) e.push('<th class="floatThead-col"/>'), f.push("<col/>"), g.push("<fthtd style='display:table-cell;height:0;width:auto;'/>");
f = f.join(""), e = e.join(""), h && (g = g.join(""), W.html(g), bb = W.find("fthtd")), Z.html(e), $ = Z.find("th"), V || U.html(f), _ = U.find("col"), T.html(f), ab = T.find("col")
}
return b
}
function p() {
if (!E) {
if (E = !0, J) {
var a = z.width(),
b = Q.width();
a > b && z.css("minWidth", a)
}
z.css(db), S.css(db), S.append(A), B.before(Y), i()
}
}
function q() {
E && (E = !1, J && z.width(fb), Y.detach(), z.prepend(A), z.css(eb), S.css(eb))
}
function r(a) {
J != a && (J = a, X.css({
position: J ? "absolute" : "fixed"
}))
}
function s(a, b, c, d) {
return h ? c : d ? o.getSizingRow(a, b, c) : b
}
function t() {
var a, b = n();
return function () {
var c = s(z, _, bb, g);
if (c.length == b && b > 0) {
if (!V) for (a = 0; b > a; a++) _.eq(a).css("width", "");
q();
var d = [];
for (a = 0; b > a; a++) d[a] = c.get(a).offsetWidth;
for (a = 0; b > a; a++) ab.eq(a).width(d[a]), _.eq(a).width(d[a]);
p()
} else S.append(A), z.css(eb), S.css(eb), i()
}
}
function u(a) {
var b = I.css("border-" + a + "-width"),
c = 0;
return b && ~b.indexOf("px") && (c = parseInt(b, 10)), c
}
function v() {
var a, b = I.scrollTop(),
c = 0,
d = L ? K.outerHeight(!0) : 0,
e = M ? d : -d,
f = X.height(),
g = z.offset(),
i = 0;
if (O) {
var k = I.offset();
c = g.top - k.top + b, L && M && (c += d), c -= u("top"), i = u("left")
} else a = g.top - C - f + D + F.horizontal;
var l = j.scrollTop(),
m = j.scrollLeft(),
n = I.scrollLeft();
return b = I.scrollTop(),
function (k) {
if ("windowScroll" == k ? (l = j.scrollTop(), m = j.scrollLeft()) : "containerScroll" == k ? (b = I.scrollTop(), n = I.scrollLeft()) : "init" != k && (l = j.scrollTop(), m = j.scrollLeft(), b = I.scrollTop(), n = I.scrollLeft()), !h || !(0 > l || 0 > m)) {
if (R) r("windowScrollDone" == k ? !0 : !1);
else if ("windowScrollDone" == k) return null;
g = z.offset(), L && M && (g.top += d);
var o, s, t = z.outerHeight();
if (O && J) {
if (c >= b) {
var u = c - b;
o = u > 0 ? u : 0
} else o = P ? 0 : b;
s = i
} else !O && J ? (l > a + t + e ? o = t - f + e : g.top > l + C ? (o = 0, q()) : (o = C + l - g.top + c + (M ? d : 0), p()), s = 0) : O && !J ? (c > b || b - c > t ? (o = g.top - l, q()) : (o = g.top + b - l - c, p()), s = g.left + n - m) : O || J || (l > a + t + e ? o = t + C - l + a + e : g.top > l + C ? (o = g.top - l, p()) : o = C, s = g.left - m);
return {
top: o,
left: s
}
}
}
}
function w() {
var a = null,
b = null,
c = null;
return function (d, e, f) {
null == d || a == d.top && b == d.left || (X.css({
top: d.top,
left: d.left
}), a = d.top, b = d.left), e && l(), f && i();
var g = I.scrollLeft();
J && c == g || (X.scrollLeft(g), c = g)
}
}
function x() {
if (I.length) {
var a = I.width(),
b = I.height(),
c = z.height(),
d = z.width(),
e = d > a ? G : 0,
f = c > b ? G : 0;
F.horizontal = d > a - f ? G : 0, F.vertical = c > b - e ? G : 0
}
}
var y = k,
z = a(this);
if (z.data("floatThead-attached")) return !0;
if (!z.is("table")) throw new Error('jQuery.floatThead must be run on a table element. ex: $("table").floatThead();');
var A = z.find("thead:first"),
B = z.find("tbody:first");
if (0 == A.length) throw new Error("jQuery.floatThead must be run on a table that contains a <thead> element");
var C, D, E = !1,
F = {
vertical: 0,
horizontal: 0
}, G = d(),
H = 0,
I = o.scrollContainer(z) || a([]),
J = o.useAbsolutePositioning;
null == J && (J = o.scrollContainer(z).length);
var K = z.find("caption"),
L = 1 == K.length;
if (L) var M = "top" === (K.css("caption-side") || K.attr("align") || "top");
var N = a('<fthfoot style="display:table-footer-group;"/>'),
O = I.length > 0,
P = !1,
Q = a([]),
R = 9 >= g && !O && J,
S = a("<table/>"),
T = a("<colgroup/>"),
U = z.find("colgroup:first"),
V = !0;
0 == U.length && (U = a("<colgroup/>"), V = !1);
var W = a('<fthrow style="display:table-row;height:0;"/>'),
X = a('<div style="overflow: hidden;"></div>'),
Y = a("<thead/>"),
Z = a('<tr class="size-row"/>'),
$ = a([]),
_ = a([]),
ab = a([]),
bb = a([]);
if (Y.append(Z), z.prepend(U), h && (N.append(W), z.append(N)), S.append(T), X.append(S), o.copyTableClass && S.attr("class", z.attr("class")), S.attr({
cellpadding: z.attr("cellpadding"),
cellspacing: z.attr("cellspacing"),
border: z.attr("border")
}), S.css({
borderCollapse: z.css("borderCollapse"),
border: z.css("border")
}), S.addClass(o.floatTableClass).css("margin", 0), J) {
var cb = function (a, b) {
var c = a.css("position"),
d = "relative" == c || "absolute" == c;
if (!d || b) {
var e = {
paddingLeft: a.css("paddingLeft"),
paddingRight: a.css("paddingRight")
};
X.css(e), a = a.wrap("<div class='" + o.floatWrapperClass + "' style='position: relative; clear:both;'></div>").parent(), P = !0
}
return a
};
O ? (Q = cb(I, !0), Q.append(X)) : (Q = cb(z), z.after(X))
} else z.after(X);
X.css({
position: J ? "absolute" : "fixed",
marginTop: 0,
top: J ? 0 : "auto",
zIndex: o.zIndex
}), X.addClass(o.floatContainerClass), m();
var db = {
"table-layout": "fixed"
}, eb = {
"table-layout": z.css("tableLayout") || "auto"
}, fb = z[0].style.width || "";
x();
var gb, hb = function () {
(gb = t())()
};
hb();
var ib = v(),
jb = w();
jb(ib("init"), !0);
var kb = f.debounce(function () {
jb(ib("windowScrollDone"), !1)
}, 300),
lb = function () {
jb(ib("windowScroll"), !1), kb()
}, mb = function () {
jb(ib("containerScroll"), !1)
}, nb = function () {
m(), x(), hb(), ib = v(), (jb = w())(ib("resize"), !0, !0)
}, ob = f.debounce(function () {
x(), m(), hb(), ib = v(), jb(ib("reflow"), !0)
}, 1);
O ? J ? I.on(c("scroll"), mb) : (I.on(c("scroll"), mb), j.on(c("scroll"), lb)) : j.on(c("scroll"), lb), j.on(c("load"), ob), b(o.debounceResizeMs, c("resize"), nb), z.on("reflow", ob), e(z) && z.on("filter", ob).on("sort", ob).on("page", ob), z.data("floatThead-attached", {
destroy: function () {
var a = ".fth-" + y;
q(), z.css(eb), U.remove(), h && N.remove(), Y.parent().length && Y.replaceWith(A), z.off("reflow"), I.off(a), P && (I.length ? I.unwrap() : z.unwrap()), J && z.css("minWidth", ""), X.remove(), z.data("floatThead-attached", !1), j.off(a)
},
reflow: function () {
ob()
},
setHeaderHeight: function () {
i()
},
getFloatContainer: function () {
return X
},
getRowGroups: function () {
return E ? X.find("thead").add(z.find("tbody,tfoot")) : z.find("thead,tbody,tfoot")
}
}), k++
}), this
}
}(jQuery),
function (a) {
a.floatThead = a.floatThead || {}, a.floatThead._ = window._ || function () {
var b = {}, c = Object.prototype.hasOwnProperty,
d = ["Arguments", "Function", "String", "Number", "Date", "RegExp"];
return b.has = function (a, b) {
return c.call(a, b)
}, b.keys = function (a) {
if (a !== Object(a)) throw new TypeError("Invalid object");
var c = [];
for (var d in a) b.has(a, d) && c.push(d);
return c
}, a.each(d, function () {
var a = this;
b["is" + a] = function (b) {
return Object.prototype.toString.call(b) == "[object " + a + "]"
}
}), b.debounce = function (a, b, c) {
var d, e, f, g, h;
return function () {
f = this, e = arguments, g = new Date;
var i = function () {
var j = new Date - g;
b > j ? d = setTimeout(i, b - j) : (d = null, c || (h = a.apply(f, e)))
}, j = c && !d;
return d || (d = setTimeout(i, b)), j && (h = a.apply(f, e)), h
}
}, b
}()
}(jQuery);
$(document).ready(function () {
$(".sticky-header").floatThead({
scrollingTop: 50
});
});

How to sort and search dom table elements created using ajax

I tried this to search dom elements and display matching rows,but it doesnt work in some columns like duration and bytes.It works for elements which repeat for example if there are 507 value twice in bytes it works but dont work for 411. I am reading file contents and tabulating it, then need to sort rows when header is clicked and apply a filter.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: GREY;
color: #333;
font-weight: bold;
cursor:pointer;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
#sear
{
background-color: black;
height:30px;
width:105%;
align : center;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
tr:hover {
background-color: silver;
}
</style>
<meta name="viewport" content="width=device-width,height=device-height, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="sear" align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center >
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
//alert(responseText);
// console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n", CELL_DELIMITER = " ";
var tableObj = { headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(), textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length-1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length ; k++) {
var td = document.createElement('td');
/* if(k==0)
{
var d = new Date( rows[j][k]* 1000),
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2),
dd = ('0' + d.getDate()).slice(-2),
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2),
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
rows[j][k] = dd + '.' + mm + '.' + yyyy + ', ' + h + ':' + min + ' ' + ampm;
}
*/
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>
Here is the updated code:
window.onload = function() {
var demo = document.getElementById("demo");
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText = xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", "Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
if(responseText!='' && typeof responseText != 'undefined'){
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
}
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
//console.log(cell.toUpperCase())
// console.log(input.value.toUpperCase())
// console.log(cell.toUpperCase().indexOf(input.value.toUpperCase()))
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j <= rows.length - 1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};

leaflet Dynamic icon with filter

I'm trying to create an map with the leaflet-simple-csv-master (i'm a beginner). It's really nice and i'd like to show different icons with my types (for exemple 1 icon for schools, one for administrations,...). I succed to show my different icons when i have the map but when i click to the filter, my icons disappear. In fact it doesn't work because it do not recognize my variable when i use the filter and i can read that my img is no more logos/type1.png but logos/undefined.png.
This is my all code.
var basemap = new L.TileLayer(baseUrl, {maxZoom: 17, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});
var center = new L.LatLng(0, 0);
var map = new L.Map('map', {center: center, zoom: 2, maxZoom: maxZoom, layers: [basemap]});
var popupOpts = {
autoPanPadding: new L.Point(5, 50),
autoPan: true
};
var points = L.geoCsv (null, {
firstLineTitles: true,
fieldSeparator: fieldSeparator,
onEachFeature: function (feature, layer) {
var popup = '<div class="popup-content"><table class="table table-striped table-condensed">';
for (var clave in feature.properties) {
var title = points.getPropertyTitle(clave).strip();
var attr = feature.properties[clave];
if (title == labelColumn) {
layer.bindLabel(feature.properties[clave], {className: 'map-label'});
}
if (attr.indexOf('http') === 0) {
attr = '<a target="_blank" href="' + attr + '">'+ attr + '</a>';
}
if (attr) {
popup += '<tr><th>'+title+'</th><td>'+ attr +'</td></tr>';
}
}
popup += "</table></popup-content>";
layer.bindPopup(popup, popupOpts);
},
pointToLayer: function (feature, latlng) {
var logo = feature.properties['type'];
return L.marker(latlng, {
icon:L.icon({
iconUrl: 'logos/'+logo+'.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25,41],
shadowSize: [41, 41],
shadowAnchor: [13, 20]
})
});
},
filter: function(feature, layer) {
total += 1;
if (!filterString) {
hits += 1;
return true;
}
var hit = false;
var lowerFilterString = filterString.toLowerCase().strip();
$.each(feature.properties, function(k, v) {
var value = v.toLowerCase();
if (value.indexOf(lowerFilterString) !== -1) {
hit = true;
hits += 1;
return false;
}
});
return hit;
}
});
var hits = 0;
var total = 0;
var filterString;
var markers = new L.MarkerClusterGroup();
var dataCsv;
var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;
if (filterString) {
$("#clear").fadeIn();
} else {
$("#clear").fadeOut();
}
map.removeLayer(markers);
points.clearLayers();
markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);
map.addLayer(markers);
try {
var bounds = markers.getBounds();
if (bounds) {
map.fitBounds(bounds);
}
} catch(err) {
// pass
}
if (total > 0) {
$('#search-results').html("Showing " + hits + " of " + total);
}
return false;
};
var typeAheadSource = [];
function ArrayToSet(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populateTypeAhead(csv, delimiter) {
var lines = csv.split("\n");
for (var i = lines.length - 1; i >= 1; i--) {
var items = lines[i].split(delimiter);
for (var j = items.length - 1; j >= 0; j--) {
var item = items[j].strip();
item = item.replace(/"/g,'');
if (item.indexOf("http") !== 0 && isNaN(parseFloat(item))) {
typeAheadSource.push(item);
var words = item.split(/\W+/);
for (var k = words.length - 1; k >= 0; k--) {
typeAheadSource.push(words[k]);
}
}
}
}
}
if(typeof(String.prototype.strip) === "undefined") {
String.prototype.strip = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
map.addLayer(markers);
$(document).ready( function() {
$.ajax ({
type:'GET',
dataType:'text',
url: dataUrl,
contentType: "text/csv; charset=utf-8",
error: function() {
alert('Error retrieving csv file');
},
success: function(csv) {
dataCsv = csv;
populateTypeAhead(csv, fieldSeparator);
typeAheadSource = ArrayToSet(typeAheadSource);
$('#filter-string').typeahead({source: typeAheadSource});
addCsvMarkers();
}
});
$("#clear").click(function(evt){
evt.preventDefault();
$("#filter-string").val("").focus();
addCsvMarkers();
});
});

google distance matrix API 3

I have code to calculate distance place to another place using google distance matrix API, but for free its limited just 100 elements per query. So I make code for solve the problem using looping code such as for elements , My code is PHP, javascript , and I parse latitude and longitude data from MySql. Anyone know some error of my code below ? because It don't appear anything if I click calculate button. Actualy I have modifie the code from this URL https://google-developers.appspot.com/maps/documentation/javascript/examples/distance-matrix , And this is my Code :
function hitung (){
service = new google.maps.DistanceMatrixService();
for (m = 0 ; m < l-80 ; m++ ){
asal = originarray[m];
for (n = 0 ; n < l-80 ; n++ ){
tujuan = destarray [n];
calculateDistances();
}
}
}
function calculateDistances() {
//var s = 0;
//for (m = 0 ; m < l-80 ; m++ ){
// asal = originarray[m];
//for (n = 0 ; n < l-80 ; n++ ){
//servicearray[s] = new google.maps.DistanceMatrixService();
//tujuan = destarray [n];
service.getDistanceMatrix(
{
//origins: [origin1, origin2],
// destinations: [destinationA, destinationB],
origins: asal,
destinations: tujuan,
//origins: originarray,
//destinations: destarray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
// s++;
//}
// }
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
//outputDiv.innerHTML = '';
// deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
// addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
// addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: peta,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Check if you're receiving a response from Google by logging the response...
function callback(response, status) {
console.log(response);
}

Resources