Object.defineProperty called on non-object error - javascript

I have this error in jQuery about this code .. and i can't fix it .. i don't understand it and the console log ...
Code is a notifications tool in Blogger that runs cookies
Object.defineProperty called on non-object .... at Function.defineProperty ()
$(function() {
var view = settingsnoti["noti-bloghomepageUrl"];
var message = void 0 !== settingsnoti["word"] ? settingsnoti["word"] : "";
var _0x322dc6 = false !== settingsnoti["allow-noti"];
var a_second = void 0 !== settingsnoti.expires ? settingsnoti.expires : 7;
var _0x48e20c = void 0 !== settingsnoti["color"] ? settingsnoti["color"] : "#388d80";
var styleFloat = void 0 !== settingsnoti.float ? settingsnoti.float : "right";
var lessFileName = false !== settingsnoti["ltr"];
language_form = "" !== message ? message : ["تحديد الكل كمقروء", "قبول", "إلغاء", "عرض", "زيارة", "إشعار", "إعلان", "تحديث", "راجع مالجديد!!"];
var load = function(_height) {
return language_form[parseInt(_height - 1)];
};
switch (lessFileName) {
case true:
badge_dir = "ltr-badge";
break;
case false:
default:
badge_dir = "rtl-badge";
}! function($) {
var abbr;
var i = "#notification-badge";
var element = 'input[name="badge[]"]';
var value = "#notibadgeBtn";
$.fn.ihavebadge = function(name, all) {
var map_el = $(this);
var item = $.extend({
"childTypes": settingsnoti,
"delay": 1,
"expires": a_second,
"onAccept": function() {},
"ImageSize": 116,
"substring": 140,
"float": styleFloat,
"ltr": lessFileName,
"bloggcodeNAM": "PicFast",
"bloggcodeURI": "https://blogg-code.blogspot.com",
"macrosid": "AKfycbykx1ZVe0t0qmw4sZ2Pez4iYNFXnv8w6HAANNtXs5VCX38RS_A",
"noImage": "https://3.bp.blogspot.com/-7CnHTs2OKS8/Wo214lKp0KI/AAAAAAAACPk/CD1mAZz7IwI32hkGM3aVbD6Tefw78IkvgCLcBGAs/s72/no-img-300x300-blogg-code.jpg",
"Imgavatar": "https://1.bp.blogspot.com/-mP-2bvOaWuM/XAkrMTFABaI/AAAAAAAADjU/tqSHDVesLcYwQ1rXt1MVvG3TENbJqMvcQCLcBGAs/s72/no-user.png",
"Monthformat": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}, name);
var types = {
"getstyle": function(p) {
$(p).appendTo($("head"));
},
"b": function(context, data, res, a, f, cb) {
context.prop("checked", cb);
context.attr("data-auto", data).parent().css({
"background-color": res,
"opacity": a,
"pointer-events": f
});
},
"getlocation": function(index) {
if (index) {
setInterval(function() {
window.location.href = index;
}, 2E3);
}
},
"getcopyright": function(delete_behavior_form) {
var artistTrack = '<li class="notirights px ads badg_radius5 styleimpo"><label class="notirights">' + load(7) + ':</label><span class="notirights type">' + item.bloggcodeNAM + '</span><span class="notirights ilink"><a class="notirights badgehover-opa badg_radius30" href="' + item.bloggcodeURI + '" target="_blank">' + load(5) + "</a></span></li>";
if (0 !== $(".notirights").length) {
$(".notirights").each(function() {
if (($(this).css("opacity") < 1 || "hidden" == $(this).css("visibility") || $(this).is(":hidden")) && $(i).is(":visible")) {
types.getlocation(item.bloggcodeURI);
}
});
} else {
$(delete_behavior_form).prepend(artistTrack);
}
}
};
types.getstyle("<style type='text/css'>div#notification-badge .button,div#notification-badge ul li label,#notification-badge input[type=checkbox],div#notification-badge .badgehover-var:hover {color:" + _0x48e20c + ";}div#notification-badge .button.done,#notification-badge input[type=checkbox]:checked::before,div#notification-badge .ilink a {background-color:" + _0x48e20c + ";}div#notification-badge .button.done,div#notification-badge .button.cancel:hover {border: 1px solid " + _0x48e20c + ";}div#notification-badge .styleimpo {display:block!important;opacity:1!important;visibility:visible!important;width:auto!important;height:auto!important;padding:5px!important;background-color:#ffffff!important;border:1px solid" + _0x48e20c + "!important}</style>");
var pix_color = "";
Math.floor(+Math["random"]() + 1);
if ($("body").hasClass("Preview")) {
var retryLinkHref = view.replace(/\/$/, "");
} else {
retryLinkHref = window.location.origin;
}
var requestOrUrl = retryLinkHref.toLowerCase() + "/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=1&max-results=1";
$.ajax({
"url": requestOrUrl,
"dataType": "jsonp",
"type": "GET",
"success": function(xhr, status, custom) {
if ("entry" in xhr.feed) {
var i = 0;
for (; i < xhr.feed.entry.length; i++) {
var data = xhr.feed.entry[i];
var version = 0;
for (; version < data.link.length; version++) {
var result = data.link[version];
if ("replies" == (result = data.link[version]).rel && "text/html" == result.type) {
result.title;
result.href;
}
if ("alternate" == result.rel) {
var replacements = result.href;
if (-1 !== replacements.indexOf(".blogspot.")) {
replacements = replacements.replace("http://", "https://");
}
break;
}
}
var word = item.Monthformat;
var nickname = data.updated.$t;
var _0x4afe5a = nickname.substring(0, 10);
var contentId = _0x4afe5a.substring(0, 4);
var cPointX = _0x4afe5a.substring(5, 7);
var linkCssId = _0x4afe5a.substring(8, 10) + "-" + word[parseInt(cPointX - 1)] + "-" + contentId;
var _0x417c4f = (data.published.$t.substr(0, 10).replace(/\-/g, "_"), data.title.$t);
var height = item.Imgavatar;
if (void 0 !== data.author[0].uri) {
var value = data.author[0].name.$t;
if (data.author[0].gd$image.src.match("blogblog")) {
var whatToScale = height;
} else {
whatToScale = data.author[0].gd$image.src;
}
var heightInCells = whatToScale.replace(/http:\/\//, "https://").replace("/72-c/", "/s220/");
var id = data.author[0].uri.$t;
} else {
value = "Unknown";
heightInCells = height;
id = "javascript:void(0)";
}
if (void 0 !== data.media$thumbnail) {
var entryOrArray = data.media$thumbnail.url;
var id = item.ImageSize;
var timestamp = entryOrArray.replace(/http:\/\//, "https://").replace("/s72-c/", "/s" + id + "/").replace("?imgmax=800", "");
} else {
if (void 0 !== data.content && null != data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/)) {
var shapePathsCollection = data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/).pop();
if (11 == shapePathsCollection.length) {
timestamp = "//img.youtube.com/vi/" + shapePathsCollection + "/0.jpg";
}
} else {
if (void 0 !== data.content && null != data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)) {
timestamp = data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
timestamp = item.noImage;
}
}
}
if (void 0 !== data.summary) {
var matches = data.summary.$t.replace(/<\S[^>]*>/g, "");
var resizewidth = matches.substring(0, item.substring) + "...";
if (300 < matches.length) {
matches.substring(0, 170);
}
if (100 < matches.length) {
matches.substring(0, 100);
}
} else {
if (void 0 !== data.content) {
var result = data.content.$t.replace(/(<([^>]+)>)/gi, "");
resizewidth = result.substring(0, item.substring) + "...";
if (300 < result.length) {
result.substring(0, 170);
}
if (100 < result.length) {
result.substring(0, 100);
}
} else {
resizewidth = "";
}
}
var _0xb2707 = data.id.$t.split(".post-").pop();
pix_color = pix_color + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietypeupdated-' + _0xb2707 + '" name="badge[]" value="updated-' + _0xb2707 + '" data-auto="off"/><label for="badge-id-cookietypeupdated-' + _0xb2707 + '">' + load(8) + ':</label>' + load(9) + '<abbr class="timeago idate badg_radius30" title="' + nickname + '">' + linkCssId + '</abbr><span class="icontent"><a class="badgehover-var" href="' + replacements + '" target="_blank"><img class="badg_radius5" src="' + timestamp + '"/>' + _0x417c4f + '</a></span><span class="inameauthor"><a class="badgehover-var" href="' + id + '" target="_blank" rel="nofollow"><img class="badg_radius100" src="' + heightInCells + '"/><i class="authorname">' + value + '</i></a></span></li>');
}
}
var isScaytNode = clone("badgeControl");
var workspace = clone("badgeControlPrefs");
if (isScaytNode && workspace && "reinit" != all) {
var item2 = true;
if (false == isScaytNode) {
item2 = false;
}
filter(item2, item.expires, i);
} else {
$(i).remove();
var summaryHtml = "";
preferences = JSON.parse(workspace);
$.each(item.childTypes, function(canCreateDiscussions, url) {
if ("" !== url.type && "" !== url.value && "" !== url.link && url.type) {
var th_field = "";
if (false !== url.link) {
th_field = '<span class="ilink"><a class="badgehover-opa badg_radius30" href="' + url.link + '" target="_blank">' + load(4) + '</a></span>';
}
summaryHtml = summaryHtml + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietype' + url.value + '" name="badge[]" value="' + url.value + '" data-auto="off"/><label for="badge-id-cookietype' + url.value + '">' + load(6) + ':</label><span class="type">' + url.type + '</span>' + th_field + '</li>');
}
});
var artistTrack = '<div id="notification-badge" class="' + badge_dir + 'badg_shadowkit badg_radius2" style="display: none;"><div id="badge-types"><p><button class="button btn-top select" id="badge-btn-select" type="button">' + load(1) + '</button></p><ul>' + summaryHtml + pix_color + '</ul></div><p><button class="button btn-bottom done badgehover-opa badg_radius5" id="badge-btn-done" type="button">' + load(2) + '</button><button class="button btn-bottom cancel badg_radius5" id="badge-btn-cancel" type="button">' + load(3) + '</button></p></div>';
$(map_el).append(artistTrack);
setTimeout(function() {
$.each(preferences, function(canCreateDiscussions, domRootID) {
if (1 != $('#badge-id-cookietype' + domRootID).length) {
abbr = $('#badge-id-cookietype' + domRootID).length;
}
});
var d = preferences.length;
var v = $(element).length;
var m = v - d;
if (0 == abbr && (m = v - d + 1), d || (m = v), 10 < m && (m = "+9"), 0 < m) {
var artistTrack = '<span class="' + badge_dir + 'badge alert badg_radius100">' + m + '</span>';
$(value).append(artistTrack).addClass("Animat-notifications");
}
}, item.delay);
$(window).scroll(function() {
fn(i, value);
});
$("body").on("click", value, function() {
if ($(i).is(":hidden")) {
$(i).hide(function() {
$(".badge").remove();
$(value).addClass("active").removeClass("Animat-notifications");
var x;
var orig_top = $(value).offset().top + $(value).height();
if ("left" === item.float) {
x = $(value).offset().left;
$(this).css({
"top": orig_top + "px",
"left": x + "px"
});
} else {
if ("right" === item.float) {
x = $(window).width() - ($(value).offset().left + $(value).outerWidth());
$(this).css({
"top": orig_top + "px",
"right": x + "px"
});
}
}
$.each(preferences, function(canCreateDiscussions, conid) {
if ($.fn.ihavebadge.preference(conid)) {
types.b($("#badge-id-cookietype" + conid), "on", "white", ".4", "none", true);
}
});
}).fadeIn(100);
}
types.getcopyright("#notification-badge ul");
});
$(i).click(function(canCreateDiscussions) {
if ("BUTTON" !== canCreateDiscussions.target.nodeName) {
canCreateDiscussions.stopPropagation();
}
});
$(element).on("change", function() {
if (this.checked) {
types.b($(this), "on", "white", ".4", "auto");
} else {
types.b($(this), "off", "#f8f8f8", "1", "auto");
}
});
$("body").on("click", "#badge-btn-select", function() {
types.b($(element), "on", "white", ".4", "auto", true);
$("#badge-btn-done").trigger("click");
});
$("body").on("click", "#badge-btn-cancel", function() {
fn(i, value);
});
$("body").on("click", "#badge-btn-advanced", function() {
types.b($(element), "off", "#f1f1f1", "1", "auto", false);
});
$("body").on("click", "#badge-btn-done", function() {
filter(true, item.expires, i);
var data = [];
$.each($(element).serializeArray(), function(canCreateDiscussions, nodes) {
data.push(nodes.value);
var item = '#badge-id-cookietype' + nodes.value;
types.b($(item), "on", "white", ".4", "none");
});
trigger("badgeControlPrefs", JSON.stringify(data), 365);
item.onAccept.call(this);
});
}
}
});
};
$.fn.ihavebadge.cookie = function() {
var message = clone("badgeControlPrefs");
return JSON.parse(message);
};
$.fn.ihavebadge.preference = function(_relatedTarget) {
var currentLineStylesCloned = clone("badgeControl");
var data = clone("badgeControlPrefs");
return data = JSON.parse(data), false !== currentLineStylesCloned && (false !== data && -1 !== data.indexOf(_relatedTarget));
};
var filter = function(key, val, enhanced) {
trigger("badgeControl", key, val);
$(enhanced).fadeOut("fast", function() {
fn(this, value);
});
};
var fn = function(id, el) {
$(id).removeAttr("style");
$(el).removeClass("active");
};
var trigger = function(y, x, keys) {
var expected_date2 = new Date;
expected_date2.setTime(expected_date2.getTime() + 24 * keys * 60 * 60 * 1E3);
var _0x491ad2 = "expires=" + expected_date2.toUTCString();
return document.cookie = y + "=" + x + ";" + _0x491ad2 + ";path=/", clone(y);
};
var clone = function(method) {
var data = method + "=";
var PL$13 = decodeURIComponent(document.cookie).split(";");
var PL$17 = 0;
for (; PL$17 < PL$13.length; PL$17++) {
var PL$6 = PL$13[PL$17];
for (;
" " == PL$6.charAt(0);) {
PL$6 = PL$6.substring(1);
}
if (0 === PL$6.indexOf(data)) {
return PL$6.substring(data.length, PL$6.length);
}
}
return false;
};
}(jQuery);
var am_Overlay = {
"onAccept": function() {
console.log("%cnotification saved...", "color:tomato");
}
};
if (true == _0x322dc6) {
$("body").ihavebadge(am_Overlay, "reinit");
} else {
$("#notibadgeBtn").remove();
}
});
how i can fixed it i want to help please .. and thanks you for all :)

Related

JSON Parse issue in React-Native

I'm so lost.
I keep getting this error:
"SAVED SCREEN NETWORK ERROR: , [SyntaxError: JSON Parse error: Unrecognized token '<']
at node_modules/color-string/index.js:90:16 in cs.get.rgb" (Line 90 is right below my console.log in the code down below)
This part:
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
But when I check the node_modules, I can't understand at all where its even using JSON. I console logged the match and all I'm getting is this:
Array [
"rgb(28, 28, 30)",
"28",
"28",
"30",
undefined,
undefined,
]
I literally don't know what to do anymore, so I'm hoping someone more experienced can help me out on this.
/* MIT license */
var colorNames = require('color-name');
var swizzle = require('simple-swizzle');
var hasOwnProperty = Object.hasOwnProperty;
var reverseNames = {};
// create a list of reverse color names
for (var name in colorNames) {
if (hasOwnProperty.call(colorNames, name)) {
reverseNames[colorNames[name]] = name;
}
}
var cs = module.exports = {
to: {},
get: {}
};
cs.get = function (string) {
var prefix = string.substring(0, 3).toLowerCase();
var val;
var model;
switch (prefix) {
case 'hsl':
val = cs.get.hsl(string);
model = 'hsl';
break;
case 'hwb':
val = cs.get.hwb(string);
model = 'hwb';
break;
default:
val = cs.get.rgb(string);
model = 'rgb';
break;
}
if (!val) {
return null;
}
return {model: model, value: val};
};
cs.get.rgb = function (string) {
if (!string) {
return null;
}
var abbr = /^#([a-f0-9]{3,4})$/i;
var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var keyword = /^(\w+)$/;
var rgb = [0, 0, 0, 1];
var match;
var i;
var hexAlpha;
if (match = string.match(hex)) {
hexAlpha = match[2];
match = match[1];
for (i = 0; i < 3; i++) {
// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
var i2 = i * 2;
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha, 16) / 255;
}
} else if (match = string.match(abbr)) {
match = match[1];
hexAlpha = match[3];
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
}
} else if (match = string.match(rgba)) {
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i + 1], 0);
}
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(keyword)) {
if (match[1] === 'transparent') {
return [0, 0, 0, 0];
}
if (!hasOwnProperty.call(colorNames, match[1])) {
return null;
}
rgb = colorNames[match[1]];
rgb[3] = 1;
return rgb;
} else {
return null;
}
for (i = 0; i < 3; i++) {
rgb[i] = clamp(rgb[i], 0, 255);
}
rgb[3] = clamp(rgb[3], 0, 1);
return rgb;
};
cs.get.hsl = function (string) {
if (!string) {
return null;
}
var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var s = clamp(parseFloat(match[2]), 0, 100);
var l = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
return null;
};
cs.get.hwb = function (string) {
if (!string) {
return null;
}
var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var w = clamp(parseFloat(match[2]), 0, 100);
var b = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
return null;
};
cs.to.hex = function () {
var rgba = swizzle(arguments);
return (
'#' +
hexDouble(rgba[0]) +
hexDouble(rgba[1]) +
hexDouble(rgba[2]) +
(rgba[3] < 1
? (hexDouble(Math.round(rgba[3] * 255)))
: '')
);
};
cs.to.rgb = function () {
var rgba = swizzle(arguments);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
};
cs.to.rgb.percent = function () {
var rgba = swizzle(arguments);
var r = Math.round(rgba[0] / 255 * 100);
var g = Math.round(rgba[1] / 255 * 100);
var b = Math.round(rgba[2] / 255 * 100);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
};
cs.to.hsl = function () {
var hsla = swizzle(arguments);
return hsla.length < 4 || hsla[3] === 1
? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
};
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
cs.to.hwb = function () {
var hwba = swizzle(arguments);
var a = '';
if (hwba.length >= 4 && hwba[3] !== 1) {
a = ', ' + hwba[3];
}
return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
};
cs.to.keyword = function (rgb) {
return reverseNames[rgb.slice(0, 3)];
};
// helpers
function clamp(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = Math.round(num).toString(16).toUpperCase();
return (str.length < 2) ? '0' + str : str;
}

"Length" Type Uncaught Error : Jquery, Codeigniter

Full Code: custom.js
function addAlert(message, type) {
$('.alerts-con').empty().append(
'<div class="alert alert-' + type + '">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + message + '</div>');
}
function widthFunctions(e) {
$(".tip").tooltip();
$(".chzn-container").css('width', '100%');
var bH = $('body').height();
var nH = $('.navbar').outerHeight();
var mH = $('.mainbar').height();
var sbH = bH - nH;
if ( mH > sbH ) {
$('.sidebar-inner').css('height', (mH+20)+'px');
} else {
$('.sidebar-inner').css('height', (sbH)+'px');
}
}
$(document).ready(function () {
widthFunctions();
});
// $(window).load(function () {
// setTimeout(widthFunctions, 2000);
// });
$(window).bind("resize", widthFunctions);
//$('.container').bind("resize", widthFunctions);
/* Navigation */
$(document).ready(function() {
$(window).resize(function() {
if($(window).width() >= 765){
$(".sidebar .sidebar-inner").css('width', '100%');
$(".sidebar .sidebar-inner").slideDown(350);
}
else{
$(".sidebar .sidebar-inner").slideUp(350);
}
});
});
$(document).ready(function(){
$(".has_submenu > a").click(function(e){
e.preventDefault();
var menu_li = $(this).parent("li");
var menu_ul = $(this).next("ul");
if(menu_li.hasClass("open")){
menu_ul.slideUp(350);
menu_li.removeClass("open")
}
else{
$(".navi > li > ul").slideUp(350);
$(".navi > li").removeClass("open");
menu_ul.slideDown(350);
menu_li.addClass("open");
}
});
});
$(document).ready(function(){
$(".sidebar-dropdown a").on('click',function(e){
e.preventDefault();
if(!$(this).hasClass("dropy")) {
$(".sidebar .sidebar-inner").slideUp(350);
$(".sidebar-dropdown a").removeClass("dropy");
$(".sidebar .sidebar-inner").slideDown(350);
$(this).addClass("dropy");
}
else if($(this).hasClass("dropy")) {
$(this).removeClass("dropy");
$(".sidebar .sidebar-inner").slideUp(350);
}
});
});
$(".totop").hide();
$(function(){
$(window).scroll(function(){
if ($(this).scrollTop()>300)
$('.totop').slideDown();
else
$('.totop').slideUp();
});
$('.totop a').click(function (e) {
e.preventDefault();
$('body,html').animate({scrollTop: 0}, 500);
});
});
$(function() {
$( "#todaydate" ).datepicker({
onSelect: function(dateText, inst) {
var sp = dateText.split('/')
var href = Site.base_url+'calendar/get_day_event/' + sp[2]+'-'+sp[0]+'-'+sp[1];
$.get(href, function( data ) {
$("#simModal").html(data).appendTo("body").modal();
});
}
});
});
/* Modal fix */
$('.modal').appendTo($('body'));
$(document).ready(function() {
$('#gen_ref').click(function(){
$(this).parent('.input-group').children('input').val(getRandomRef());
});
// $('#simModal').on('hidden.bs.modal', function() {
// $(this).find('.modal-dialog').empty();
// $(this).removeData('bs.modal');
// });
// $('#simModal2').on('hidden.bs.modal', function () {
// $(this).find('.modal-dialog').empty();
// $(this).removeData('bs.modal');
// $('#simModal').css('zIndex', '1050');
// $('#simModal').css('overflow-y', 'scroll');
// });
// $('#simModal2').on('show.bs.modal', function () {
// $('#simModal2').appendTo('body');
// $('#simModal').css('zIndex', '1040');
// });
// $('.modal').on('show.bs.modal', function () {
// $('#modal-loading').show();
// $('.blackbg').css('zIndex', '1041');
// $('.loader').css('zIndex', '1042');
// }).on('hide.bs.modal', function () {
// $('#modal-loading').hide();
// $('.blackbg').css('zIndex', '3');
// $('.loader').css('zIndex', '4');
// });
$("form select").chosen({no_results_text: "No results matched", disable_search_threshold: 5, allow_single_deselect:true, width: '100%'});
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show');
});
$('#myTab a').first().tab('show');
if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
return $('a[data-toggle="tab"]').on('shown', function(e) {
return location.hash = $(e.target).attr('href').substr(1);
});
});
function fld(oObj) {
if (oObj != null) {
var aDate = oObj.split('-');
var bDate = aDate[2].split(' ');
year = aDate[0], month = aDate[1], day = bDate[0], time = bDate[1];
if (Site.dateFormats.js_sdate == 'dd-mm-yyyy')
return day + "-" + month + "-" + year + " " + time;
else if (Site.dateFormats.js_sdate === 'dd/mm/yyyy')
return day + "/" + month + "/" + year + " " + time;
else if (Site.dateFormats.js_sdate == 'dd.mm.yyyy')
return day + "." + month + "." + year + " " + time;
else if (Site.dateFormats.js_sdate == 'mm/dd/yyyy')
return month + "/" + day + "/" + year + " " + time;
else if (Site.dateFormats.js_sdate == 'mm-dd-yyyy')
return month + "-" + day + "-" + year + " " + time;
else if (Site.dateFormats.js_sdate == 'mm.dd.yyyy')
return month + "." + day + "." + year + " " + time;
else
return oObj;
} else {
return '';
}
}
function fsd(oObj) {
if (oObj != null) {
var aDate = oObj.split('-');
if (Site.dateFormats.js_sdate == 'dd-mm-yyyy')
return aDate[2] + "-" + aDate[1] + "-" + aDate[0];
else if (Site.dateFormats.js_sdate === 'dd/mm/yyyy')
return aDate[2] + "/" + aDate[1] + "/" + aDate[0];
else if (Site.dateFormats.js_sdate == 'dd.mm.yyyy')
return aDate[2] + "." + aDate[1] + "." + aDate[0];
else if (Site.dateFormats.js_sdate == 'mm/dd/yyyy')
return aDate[1] + "/" + aDate[2] + "/" + aDate[0];
else if (Site.dateFormats.js_sdate == 'mm-dd-yyyy')
return aDate[1] + "-" + aDate[2] + "-" + aDate[0];
else if (Site.dateFormats.js_sdate == 'mm.dd.yyyy')
return aDate[1] + "." + aDate[2] + "." + aDate[0];
else
return oObj;
} else {
return '';
}
}
function formatNumber(x, d) {
if(!d) { d = Site.Settings.decimals; }
return accounting.formatNumber(x, d, Site.Settings.thousands_sep == 0 ? ' ' : Site.Settings.thousands_sep, Site.Settings.decimals_sep);
}
function formatMoney(x, symbol) {
if(!symbol) { symbol = ""; }
return accounting.formatMoney(x, symbol, Site.Settings.decimals, Site.Settings.thousands_sep == 0 ? ' ' : Site.Settings.thousands_sep, Site.Settings.decimals_sep, "%s%v");
}
function decimalFormat(x) {
if (x != null) {
return '<div class="text-center">'+formatNumber(x)+'</div>';
} else {
return '<div class="text-center">0</div>';
}
}
function currencyFormat(x) {
if (x != null) {
return '<div class="text-right">'+formatMoney(x)+'</div>';
} else {
return '<div class="text-right">0</div>';
}
}
function formatDecimal(x) {
return parseFloat(x).toFixed(decimals);
}
function getRandomRef() {
var min = 10000000000000, max = 9999999999999999;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function formatDecimal(x, d) {
if(!d) { d = Site.Settings.decimals; }
return parseFloat(accounting.formatNumber(x, d, Site.Settings.thousands_sep == 0 ? ' ' : Site.Settings.thousands_sep, Site.Settings.decimals_sep));
}
function cf(x) { return currencyFormat(x); }
function pf(x) { return parseFloat(x); }
// for add edit pages
var rate_origin;
function suggestions() {
$(".suggestions").autocomplete({
source: Site.base_url+'products/suggestions',
select: function (event, ui) {
var row = $(this).closest('tr');
var sel_item = ui.item;
row.find('.price').val(sel_item.price);
rate_origin = sel_item.price;
var price = parseInt(row.find('.price').val());
var gst = parseInt(price * 0.14);
row.find('.hsn').val(sel_item.hsn);
row.find('.cgst').val(gst);
var igst = $('#gst').val();
if(igst == 'sgst'){
row.find('.igst').val('NIL');
row.find('.sgst').val(gst);
}else {
row.find('.sgst').val('NIL');
row.find('.igst').val(gst);
}
rate = row.find('.price').val();
var data = $('#order_tax').val();
var cgst = row.find('.cgst').val();
var sgst = row.find('.sgst').val();
var igst = row.find('.igst').val();
if(data == 'incl'){
if($('#gst').val() == 'sgst'){
console.log('Hello SGST Type'+rate+data+cgst+sgst);
var change_price = (rate - cgst) - sgst;
row.find('.price').val(change_price);
}else {
console.log('Hello IGST Type '+rate+data+cgst+igst);
var change_price = (rate - cgst) - igst;
row.find('.price').val(change_price);
}
}
if(row.find('.sqft').val() == 0){
row.find('.sqft').val(1).change();
}
if (sel_item.details != '' && sel_item.details != null) {
row.find('.details-con').css('display', 'block');
row.find('.details').val(sel_item.details);
}
calculateTotal();
},
minLength: 1,
autoFocus: false,
delay: 250,
response: function (event, ui) {
if (ui.content.length == 1 && ui.content[0].id != 0) {
ui.item = ui.content[0];
$(this).val(ui.item.label);
$(this).removeClass('ui-autocomplete-loading');
}
},
});
$(".price").select(calculateTotal());
}
function calculateTotal() {
if (typeof counter !== 'undefined') {
var total = 0, total_tax_amount = 0; var row_total = 0;
for (i = 1; i < (counter+1); i++) {
var shipping = parseFloat($('#shipping').val() ? $('#shipping').val() : 0);
var row = $('#'+i);
var quantity = row.find('.sqft').val(),
product = row.find('.suggestions').val(),
price = row.find('.price').val(),
discount = row.find('.discount').val(),
tax = row.find('.cgst').val(),
subtotal = row.find('.subtotal');
if (quantity && product && price) {
var product_discount = 0, product_tax = 0;
/*if(Site.Settings.product_discount > 0) {
if (discount) {
if (discount.indexOf("%") !== -1) {
var pds = discount.split("%");
if (!isNaN(pds[0])) {
product_discount = formatDecimal((((price) * parseFloat(pds[0])) / 100), 4);
}
} else {
product_discount = formatDecimal(discount, 4);
}
}
}*/
/*if(Site.Settings.default_tax_rate > 0) {
$.each(tax_rates, function () {
if (this.id == tax) {
if (this.type == 1 && this.rate != 0) {
product_tax = formatDecimal((((price) * 28) / 100), 4);
} else {
product_tax = parseFloat(28/100);
}
}
});
}*/
var data = $('#order_tax').val();
if(data == 'incl'){
row_total = parseInt(price) * parseInt(quantity);
}else{
row_total = rate_origin;
}
var totaltax = parseInt(row.find('.cgst').val()) + parseInt(row.find('.sgst').val());
total_tax_amount += totaltax;
subtotal.val(formatMoney(row_total));
total += row_total;
}
}
$('.total_amount').text(formatMoney(total));
console.log("Total Tax Amount : "+total_tax_amount);
$('#order_tax_total').text(formatMoney(total_tax_amount));
if ($('#order_discount').val()) {
order_discount_val = $('#order_discount').val();
if (order_discount_val.indexOf("%") !== -1) {
var pds = order_discount_val.split("%");
if (!isNaN(pds[0])) {
order_discount = formatDecimal((((total) * parseFloat(pds[0])) / 100), 4);
}
} else {
order_discount = formatDecimal(order_discount_val, 4);
}
} else {
order_discount = 0;
}
/*if ($('#order_tax').val()) {
order_tax_val = $('#order_tax').val();
$.each(tax_rates, function () {
if (this.id == order_tax_val) {
if (this.type == 1 && this.rate != 0) {
order_tax = formatDecimal((((total - order_discount) * this.rate) / 100), 4);
} else {
order_tax = parseFloat(this.rate);
}
}
});
} else {
order_tax = 0;
}*/
grand_total = total + shipping;
$('#order_discount_total').text(formatMoney(total));
$('#grand_total').text(formatMoney(grand_total));
}
}
$(document).ready(function() {
$(document).on('click', '[data-toggle="ajax-modal"]', function (e) {
e.preventDefault();
var link = $(this).attr('href');
$.get(link).done(function(data) {
$('#myModal').html(data)
// .append("<script src='"+assets+"js/modal.js' />")
.modal();
});
return false;
});
$(document).on('click', '[data-toggle="modal"]', function (e) {
e.preventDefault();
var tm = $(this).attr('data-target');
$(tm).appendTo('body').modal('show');
return false;
});
$("#addButton").click(function () {
var newTr = $('<tr></tr>').attr("id", counter);
var row_hrml = '';
row_hrml += '<td style="width: 20px; text-align: center; padding-right: 10px;">'+ counter +'</td>';
row_hrml += '<td><input type="text" class="quantity form-control input-sm" name="quantity[]" id="quantity-' + counter + '" value="" style="min-width: 70px; text-align: center;" /></td>';
row_hrml += '<td><div class="input-group"><input type="text" name="product[]" id="product-' + counter + '" value="" class="form-control input-sm suggestions" maxlength="80"><span class="input-group-addon"><i class="fa fa-file-text-o pointer details"></i></span></div><div class="details-con details-con-' + counter + '" style="display:none;"><textarea style="margin-top:5px;padding:5px 10px;height:60px;" class="form-control" name="details[]" id="details-' + counter + '" maxlength="255"></textarea></div></td>';
row_hrml += '<td><input type="text" name="price[]" id="price-' + counter + '" value="" class="price form-control input-sm text-right" style="min-width: 100px;"></td>';
if (Site.Settings.product_discount == 1) {
row_hrml += '<td><input type="text" name="discount[]" id="discount-' + counter + '" value="" class="discount form-control input-sm"></td>';
}
if (Site.Settings.default_tax_rate == 1) {
row_hrml += '<td><select class="tax form-control input-sm" style="min-width: 100px;" name="tax_rate[]" id="tax_rate-' + counter + '">';
$.each(tax_rates, function () {
row_hrml += '<option value="'+ this.is +'">'+ this.name +'</option>';
});
row_hrml += '</select></td>';
}
row_hrml += '<td><input type="text" name="subtotal[]" readonly id="subtotal-' + counter + '" value="" class="subtotal form-control input-sm text-right" tabindex="-1"></td>';
newTr.html(row_hrml);
newTr.appendTo("#dyTable");
counter++;
$("form select").chosen({no_results_text: "No results matched", disable_search_threshold: 5, allow_single_deselect:true, width: '100%'});
suggestions();
});
$("#removeButton").click(function () {
if (counter <= no_of_rows) {
alert(lang.not_allowed);
return false;
}
counter--;
$("#"+counter).remove();
});
$( "#customer" ).change(function () {
if($(this).val() == 'new')
$('#customerForm').slideDown('100');
else
$('#customerForm').slideUp('100');
});
$(document).on ('blur', '.suggestions', function() {
var row = $(this).closest('tr');
var v = $(this).val();
var q = row.find('.quantity');
var qv = row.find('.quantity').val();
if (qv.length == 0 && v.length != 0 ) {
$(q).val(1).change();
}
});
$(document).on('click', '.details', function(){
$(this).parents('.input-group').next('.details-con').toggle();
});
$(document).on('change', '#shipping, #order_discount, #order_tax, .quantity, .price, .discount, .tax', function() {
calculateTotal();
});
$(".notes").autocomplete({
source: Site.base_url+'sales/notes',
minLength: 2,
autoFocus: false,
delay: 500,
response: function (event, ui) {
if (ui.content.length == 1 && ui.content[0].id != 0) {
ui.item = ui.content[0];
$(this).val(ui.item.label);
$(this).removeClass('ui-autocomplete-loading');
}
},
});
$("form select").chosen({no_results_text: "No results matched", disable_search_threshold: 5, allow_single_deselect:true, width: '100%'});
$( ".datetime" ).datetimepicker({format: Site.dateFormats.js_ldate, autoclose: true, weekStart: 1, showMeridian: true, todayBtn: true});
$( ".date" ).datetimepicker({format: Site.dateFormats.js_sdate, autoclose: true, todayBtn: true, minView: 2});
$('.modal').on('show.bs.modal', function (e) {
$( ".datetime" ).datetimepicker({format: Site.dateFormats.js_ldate, autoclose: true, weekStart: 1, showMeridian: true, todayBtn: true});
$( ".date" ).datetimepicker({format: Site.dateFormats.js_sdate, autoclose: true, todayBtn: true, minView: 2});
})
suggestions();
setTimeout(function(){ calculateTotal(); }, 1000);
});
JavaScript(Error Section): custom.js
$(document).on ('blur', '.suggestions', function() {
var row = $(this).closest('tr');
var v = $(this).val();
var q = row.find('.quantity');
var qv = row.find('.quantity').val();
if (qv.length == 0 && v.length != 0 ) {
$(q).val(1).change();
}
});
Error Msg:
http://[::1]/RDS/smgp-invoice/themes/default/assets/js/custom.js:481
Uncaught TypeError: Cannot read property 'length' of undefined
at HTMLInputElement. (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/custom.js:481)
at HTMLDocument.dispatch (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/jquery.js:3074)
at HTMLDocument.elemData.handle (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/jquery.js:2750)
at Object.trigger (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/jquery.js:2986)
at Object.simulate (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/jquery.js:3301)
at HTMLDocument.handler (http://[::1]/RDS/smgp-invoice/themes/default/assets/js/jquery.js:3552)
I dont know what really to do??
any Possible solutions??
Thanks in advance...

Add event listener that tracks event and clicked object?

I have an event listener that captures the event, but I want to also capture which item was clicked. This is my code:
$(document).ready(function () {
function shareEventHandler(evt) {
if (evt.type === 'addthis.menu.share') {
//alert(typeof (evt.data)); // evt.data is an object hash containing all event data
//alert(evt.data.service);
if (evt.data.service === "tweet") {
if (blogCollection !== null) {
if (blogCollection.length) {
var result = $.grep(blogCollection, function (item) { return evt.data.url.indexOf(item.BlogUrl) > -1 });
var newArr = [];
if (result.length == 0) {
// no item
return;
} else {
var item = result[0];
alert(item.BlogTitle);
}
}
}
xt_click(this, 'C', item.BlogXtn2 + ', [' + item.BlogParentTitle + ']::[add_this]::[tweet]::[' + item.BlogTitle + ']', 'A');
}
}
}
addthis.addEventListener('addthis.menu.share', shareEventHandler);
});
I want to pass this into shareEventHandler() so that I can get the properties and the parent objects of the addThis button that was clicked, but I'm not sure how to pass it into the function.
Edit: the entire file
addthis.init();
var blogCollection;
var pageURL = location.protocol + '//' + location.host + location.pathname;
var nameOfActiveClass = "blogCategoryActive";
var category = getUrlVars()["category"];
if (category == "" || category === undefined) {
category = "All";
}
// Retrieve blogId value
if ($(".blog-wrapper").length > 0) {
var blogId = $(".blog-wrapper").attr("data-blogid");
var blogCount = $(".blog-wrapper").attr("data-blogcount");
}
// Populate the Blog Header navigation
getHeaderBlogNavigation(blogId);
// This flag controls whether to show the View more button or not
var showViewMoreFlag = true;
// Getting the correct start index
var start = getUrlVars()["start"];
if (start == "" || start == undefined) {
start = 0;
}
if (isNaN(start)) {
start = start.replace(/\D/g, '');
}
// Getting the correct end index
var end = getUrlVars()["end"];
if (end == "" || end == undefined) {
end = blogCount;
}
/*if (isNaN(end)) {
end = end.replace(/\D/g, '');
}*/
// Popluates the initial Blog post on page load
generateBlogPosts(category, start, blogCount, blogId);
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
} else {
$('.blog-more-posts').show();
}
// This function Populates the Blog Category Navigation
function getHeaderBlogNavigation(blogId) {
var end = getUrlVars()["end"];
if (end == "" || end == undefined) {
end = blogCount;
}
if (category.toLowerCase() === "all")
{
$("#Blog-Category-Navigation").append("<li class='selected " + nameOfActiveClass + "'><a class='selected " + nameOfActiveClass + "' href='" + pageURL + "?category=All&start=0&end=" + end + "'>All</a></li>");
} else {
$("#Blog-Category-Navigation").append("<li><a href='" + pageURL + "?category=All&start=0&end=" + end + "'>All</a></li>");
}
var data = "{blogId:'" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/BlogCategoryList.asmx/CategoryList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var categoryCollection = response.d;
//alert("success lis");
if (categoryCollection.length) {
for (var i = 0; i < categoryCollection.length; i++) {
$("#Blog-Category-Navigation").append(getHeaderNavigationHTML(categoryCollection[i], blogId));
}
}
},
error: function(res) {}
});
}
function getHeaderNavigationHTML(categoryName, blogId) {
var catName = category.replace(/\s/g, '');
var catNameFromSc = categoryName.replace(/\s/g, '');
var anchorTag = "<a class='selected " + nameOfActiveClass + "' onclick='getBlogByCategory(this,\"" + blogId + "\");' href='javascript:void(0);'>" + categoryName + "</a>";
if (catName == catNameFromSc) {
return "<li class='" + nameOfActiveClass + "'>" + anchorTag + "</li>";
}
return "<li>" + anchorTag + "</li>";
}
function generateBlogPosts(categoryString, startIndex, endIndex, blogId) {
// Increased endIndex by 1 to check if there are more items to display
var count = parseInt(endIndex) + 1;
var data = "{filterName:'" + categoryString + "', startIndex:" + startIndex + ", count: " + count + ", blogId: '" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/FetchBlogPost.asmx/BlogList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
blogCollection = response.d;
if (blogCollection !== null) {
if (blogCollection.length) {
var numberOfBlogPosts = blogCollection.length;
if (numberOfBlogPosts == count) {
numberOfBlogPosts = numberOfBlogPosts-1;
showViewMoreFlag = true;
} else {
showViewMoreFlag = false;
}
for (var i = 0; i < numberOfBlogPosts; i++) {
var item = blogCollection[i];
$("#Blog-Posts").append(GetBlogHTML(item, i));
}
reinitiateAddThis();
}
else {
showViewMoreFlag = false;
}
} else {
showViewMoreFlag = false;
}
},
error: function (res) { }
});
}
// This function returns the HTML for individual Blog posting
function GetBlogHTML(item, i) {
var summary = item.BlogSummary;
var summarySection = "<p class='post-categories'>" + item.BlogCategoryOutput + "</p></br>" +
"<p class='post-excerpt'>" + item.BlogSummary + "</p>";
var imageSection = "";
if (item.BlogImage !== null) {
imageSection = "<div class='post-image'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[image]:: [" + item.BlogTitle + "]','N')\" width=\"100%\">" +
"<img src='" + item.BlogImage + "' width=\"100%\" />" +
"</a>" +
"</div>";
}
var outPutHTML = "<li class='individualPost' >" +
"<article class='post'>" +
"<div class='post-details'>" +
"<h2 class='post-title'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[headline]:: [" + item.BlogTitle + "]','N')\" >" + item.BlogListingTitle + "</a>" +
"</h2>" +
"<p class='post-date'> By: " + item.BlogAuthor + "</p>" +
"<p class='post-date'>" + item.BlogDate + "</p>" + imageSection +
summarySection +
"<footer class='post-footer'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[read_more]:: [" + item.BlogTitle + "]','N')\" class='post-link'>Read More</a>" +
"<div class='social'>" +
"<div class='adtoolbox addthis_toolbox addthis_default_style' " +
"addthis:url='" + location.protocol + '//' + location.host + item.BlogUrl + "' addthis:title='" + item.BlogTitle + "'>" +
/*"<a class='addthis_button_facebook_like'></a>" +*/
"<a class='addthis_button_tweet'></a>" +
/*"<a class='addthis_counter addthis_pill_style'></a>" +*/
"<a style=\"background-color: rgb(115, 138, 141); margin-left: 2px; font-size: 11px; position: relative; height: 20px; padding: 1px 8px 1px 6px; font-weight: 500; color: #fff;cursor: pointer;" +
"border-radius: 3px; box-sizing: border-box; display: inline-block; vertical-align: top; zoom: 1; white-space: nowrap;\"" +
"class='addthis_button_email'>" +
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 32 32\" title=\"Email\" alt=\"Email\" style=\"width: 16px; height: 16px;\" class=\"at-icon at-icon-email\"><g><path d=\"M26.19 9.55H6.04l10.02 7.57 10.13-7.57zM16.06 19.67l-10.28-8.8v11.58h20.57V10.96l-10.29 8.71z\"></path></g></svg>" +
"<span style=\"display: inline-block; vertical-align: top; padding-top:2px;\">Email</span></a></div>" +
"</div>" +
"</footer>" +
"</div>" +
"</article></li>";
return outPutHTML;
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getParameterByName(name, url) {
if (!url) url = window.location.href;
url = url.toLowerCase(); // This is just to avoid case sensitiveness
name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();// This is just to avoid case sensitiveness for query parameter name
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function reinitiateAddThis() {
var script = '//s7.addthis.com/js/300/addthis_widget.js#domready=1';
if (window.addthis) {
window.addthis = null;
window._adr = null;
window._atc = null;
window._atd = null;
window._ate = null;
window._atr = null;
window._atw = null;
}
$.getScript(script);
}
// View more binding on click to fetch new blog posts
$(".blog-more-posts").click(function () {
var category = getUrlVars()["category"];
if (category == "" || category == undefined) {
category = "All";
}
var defaultNewBlogCount = 3;
//Add one to line up index
var newEnd = parseInt(end) + defaultNewBlogCount;
generateBlogPosts(category, end, defaultNewBlogCount, blogId);
end = newEnd;
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
}
if (addthis !== null) {
addthis.toolbox('.adtoolbox');
}
reinitiateAddThis();
});
// This function is called when we click on the Navigation links for Categories
function getBlogByCategory(element, blogId) {
var categoryName = $(element).text();
var catNameFromSc = $(element).text().replace(/\s/g, '');
var end = getUrlVars()["end"];
if (end == undefined) {
end = blogCount;
}
// Changes the URL of the page without reload
window.History.pushState('page 2', 'Blog Listing - ' + categoryName, pageURL + "?category=" + catNameFromSc + "&start=0&end="+end);
// Changing the Active class
jQuery("li").each(function () {
jQuery(this).removeClass(nameOfActiveClass);
});
jQuery(element).closest('li').addClass(nameOfActiveClass);
// Fetching new Start and end index
var start = getUrlVars()["start"];
if (start == undefined) {
start = 0;
}
start = start.replace(/\D/g, '');
// Setting the page with new Data
// Emptying the blog post from previous Category
$('#Blog-Posts').empty();
$('.blog-more-posts').hide();
generateBlogPostsOnCategoryClick(catNameFromSc, start, end, blogId);
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
} else {
$('.blog-more-posts').show();
}
}
// This function is called when we click on the Navigation links for Categories
function generateBlogPostsOnCategoryClick(categoryString, startIndex, endIndex, blogId) {
// Increased endIndex by 1 to check if there are more items to display
var count = parseInt(endIndex) + 1;
var data = "{filterName:'" + categoryString + "', startIndex:" + startIndex + ", count: " + count + ", blogId: '" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/FetchBlogPost.asmx/BlogList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var blogCollection = response.d;
if (blogCollection !== null) {
if (blogCollection.length) {
var numberOfBlogPosts = blogCollection.length;
if (numberOfBlogPosts == count) {
numberOfBlogPosts = numberOfBlogPosts-1;
showViewMoreFlag = true;
} else {
showViewMoreFlag = false;
}
for (var i = 0; i < numberOfBlogPosts; i++) {
var item = blogCollection[i];
$("#Blog-Posts").append(GetBlogHTML(item, i));
if (addthis !== null) {
addthis.toolbox('.adtoolbox');
}
}
}
else {
showViewMoreFlag = false;
}
} else {
showViewMoreFlag = false;
}
reinitiateAddThis();
}
});
}
//Analytics for add this
$(document).ready(function () {
function shareEventHandler(evt) {
if (evt.type === 'addthis.menu.share') {
//alert(typeof (evt.data)); // evt.data is an object hash containing all event data
//alert(evt.data.service);
if (evt.data.service === "tweet") {
var x = this;
if (blogCollection !== null) {
if (blogCollection.length) {
var result = $.grep(blogCollection, function (item) { return evt.data.url.indexOf(item.BlogUrl) > -1 });
var newArr = [];
for (var i = 0; i < blogCollection.length; i++) {
var blogItem = blogCollection[i];
if (evt.data.url.indexOf(blogItem.BlogUrl) > -1) {
newArr.push(blogItem);
}
}
if (result.length == 0) {
// no item
return;
} else {
var item = result[0];
}
}
}
xt_click(this, 'C', item.BlogXtn2 + ', [' + item.BlogParentTitle + ']::[add_this]::[tweet]::[' + item.BlogTitle + ']', 'A');
}
}
}
addthis.addEventListener('addthis.menu.share', shareEventHandler.bind(addthis));
});
I believe you are looking for event.target:
A reference to the object that dispatched the event.
In your case, that would be evt.target
Erica,
If I'm understanding you question, I believe you may just want to bind(this) on your addEventListener and then you should be able to access the context in which the addThis button was clicked.
addthis.addEventListener('addthis.menu.share', shareEventHandler.bind(addthis));
Maybe reading https://msdn.microsoft.com/en-us/library/dn569317(v=vs.94).aspx will help.

dynamically build a hierarchical dojo tree menu

I want to build a hierarchical dojo tree menu with folders and sub-folders from this html file:
<div id="prelude"><h2>Prélude</h2></div>
<div id="_BaseTestsAsync_00_NUnitIsWorking_Passed">_BaseTestsAsync_00_NUnitIsWorking<br/>Yo!</div>
<div id="_BaseTestsAsync_01_TwincatisRunning_Passed"><h2><font color="darkgreen">_BaseTestsAsync_01_TwincatisRunning</font></h2></div>
<div id="_BaseTestsAsync_02_CorrectPLCModuleIsActive_Passed">_BaseTestsAsync_02_CorrectPLCModuleIsActive</div>
<div id="AsynchronousTests_read1600OutsideRange_Passed"><h2>AsynchronousTests_read1600OutsideRange</h2></div>
<div id="AsynchronousTests_readNonEmpty1600_1_Passed"><h2>AsynchronousTests_readNonEmpty1600_1</h2></div>
<div id="AsynchronousTests_readUnknownRegister_Passed">AsynchronousTests_readUnknownRegister</div>
<div id="Robustness_WriteCurrentPosition_Passed"><h2><font color="darkgreen">Robustness_WriteCurrentPosition</font></h2></div>
<div id="Robustness_WriteIllegalSpeedPosition_Passed">Robustness_WriteIllegalSpeedPosition</div>
require([
"dojo/_base/declare", "dojo/_base/window", "dojo/store/Memory", "dijit/tree/ObjectStoreModel", "dijit/Tree", "dojo/domReady!"
], function (declare, win, Memory, ObjectStoreModel, Tree) {
divs = document.getElementsByTagName("DIV");
s = ""
var adivs = Array.prototype.slice.call(divs);
function rootName(name, depth) {
var lpath = name.split("_")
var limit = 0
if (lpath.length > depth) {
limit = depth
} else {
limit = lpath.length
}
var s = ""
for (m = 0; m < limit; m++) {
s = s + lpath[m] + "_"
}
//console.log("3[n: " + name + "][d: " + depth + "][lp: " + lpath + "][li: " + limit + "]->[s: " + s + "]")
return s
}
function hierarchy(arr, depth, parent) {
var s = ""
var arr2 = arr.map(function (a) {
var lpath = a.id.split("_")
var atdepth = ""
if (lpath.length > depth) {
atdepth = lpath[depth]
}
//console.log(" ***arr2[d: " + depth + "][parent: " + parent + "][ad: " + atdepth + "][id: " + a.id + "]")
return [a, atdepth]
});
var groups = {};
arr2.map(function (a) {
if (a[1] in groups) groups[a[1]].push(a[0]);
else {
groups[a[1]] = [];
groups[a[1]].push(a[0])
}
});
for (key in groups) {
//console.log(" ----groups[d: " + depth + "][k: " + key + "][gk: " + groups[key] + "][parent: " + parent + "]")
if (groups[key] === undefined) {} else {
if (groups[key].length == 1) {
var label = ""
var id = groups[key][0].id
if (id.indexOf("ailed") >= 0) {
label = "<b><font color=red>" + id + "</font></b>"
} else {
label = "<font color=darkgreen>" + id + "</font>"
}
var z = "1[d: " + depth + "][k: " + key + "][lbl: " + label + "][parent: " + parent + "], "
s = s + z
store3.put({
"id": id,
"label": label,
"type": "test",
"parent": parent
})
//console.log(" -l1-groups " + z)
} else {
var id = groups[key][0].id
var branchname = rootName(id, depth + 1)
var menuEntry = "<br/>2[d: " + depth + "][z: " + z + "][parent: " + parent + "][k: " + key + "][gkl: " + groups[key].length + "][p: " + branchname + "], "
var below = hierarchy(groups[key], depth + 1, rootName(id, depth + 1))
s = s + menuEntry + below
store3.put({
"id": branchname,
"label": branchname,
"type": "title",
"parent": parent
})
//console.log(" -l2-groups " + menuEntry)
}
}
}
return s
}
var store3 = new Memory({
data: [{
"id": "world",
"label": "Tests",
"type": "title"
}],
getChildren: function (object) {
return this.query({
parent: object.id
});
}
})
hierarchy(adivs, 0, "world");
// Create the model
var myModel = new ObjectStoreModel({
store: store3,
query: {
id: 'world'
},
labelAttr: "label"
});
// Custom TreeNode class (based on dijit.TreeNode) that allows rich text labels
var MyTreeNode = declare(Tree._TreeNode, {
_setLabelAttr: {
node: "labelNode",
type: "innerHTML"
}
});
// Create the Tree.
var tree = new Tree({
model: myModel,
_createTreeNode: function (args) {
return new MyTreeNode(args);
},
onClick: function (item) {
console.log("menuItem1: " + item.id)
menuItem = item.id
if (menuItem.length > 0) {
divtest = document.getElementById(menuItem);
divs = document.getElementsByTagName("DIV");
if (divtest != null) {
for (i = 0; i < divs.length; i++) {
if (divs[i].id.length == 0) {} else if (divs[i].id.indexOf("dijit") == 0) {} else if (divs[i].id.indexOf("mytree") == 0) {} else {
divs[i].style.display = "none";
}
}
divtest.style.display = "block";
menuItem = "#" + menuItem
} else {
for (i = 0; i < divs.length; i++) {
if (divs[i].id.length > 1) {
if (divs[i].id.indexOf(menuItem) == 0) {
divs[i].style.display = "block";
} else if (divs[i].id.indexOf("dijit") == 0) {
divs[i].style.display = "block";
} else {
divs[i].style.display = "none";
}
} else {
divs[i].style.display = "block";
}
}
menuItem = ""
}
}
}
});
tree.placeAt(win.body(), "first");
tree.startup();
});

Reorder the output of a javascript function

Here is my code. It currently creates this:
but I need it to display the days of the week below the dates. I know its probably just a matter of switching 2 lines around but my javascript skills are limited and i'm struggling. any help greatly appreciated.
var Timeline = function (container, date) {
this.daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
this.weekDays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
this.monthsOfYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
this.dayNumbers = {
"sunday": 0,
"monday": 1,
"tuesday": 2,
"wednesday": 3,
"thursday": 4,
"friday": 5,
"saturday": 6
};
this.initialize = function () {
this.isIE6 = (jQuery.browser.msie && jQuery.browser.version == "6.0");
this.container = $("#" + container);
if (!this.container.length) {
alert("can not locate container element \"" + container + "\"!");
return;
}
this.bubble = new Timeline.Bubble(this);
this.date = (date) ? date : new Date();
this.readEvents();
this.placeHolders = this.setupPlaceHolders();
this.container.addClass("timeline");
this.render();
},
this.readEvents = function () {
this.events = [];
var eventList = this.container.find("ul");
var eventItems = eventList.find("li");
for (var i = 0; i < eventItems.length; i++) {
var date = new Date(eventItems[i].getAttribute("title"));
if (date == "Invalid Date") continue;
this.events[i] = {
name: eventItems[i].className,
date: date,
day: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
content: jQuery(eventItems[i]).html()
};
}
var j, tmp, events = this.events;
for (var i = 1; i < events.length; i++) {
tmp = this.events[i];
for (j = i; j > 0 && events[j - 1].date > tmp.date; j--)
events[j] = events[j - 1];
events[j] = tmp;
}
eventList.remove();
}
this.render = function () {
this.placeHolders.arrows.empty();
this.placeHolders.top.empty();
this.placeHolders.bottom.empty();
var monthRepresentation = this.getMonthRepresentation();
for (var i = 0; i < monthRepresentation.length; i++)
this.renderDay(this.placeHolders.top, this.placeHolders.bottom, monthRepresentation[i]);
if (this.isIE6) this.handleIE6Issues();
this.setupArrows();
}
this.handleIE6Issues = function () {
var clone = this.placeHolders.top.clone(true);
this.container.append(clone);
clone.css({
left: "-1000px",
top: "-1000px"
});
var width = clone.outerWidth();
clone.remove();
this.placeHolders.top.css({
width: width + "px"
});
this.placeHolders.bottom.css({
width: width + "px"
});
}
this.renderDay = function (topRow, bottomRow, data) {
var cssClass = "";
cssClass += (this.isToday(data.number)) ? "today" : "";
cssClass += (data.events.length) ? " event" : "";
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
nameEl = topRow.find("div:last");
numbEl = bottomRow.find("div:last");
if (data.events.length == 0) return;
var self = this;
var enterClosure = function (e) {
self.onMouseEnter(e);
};
var leaveClosure = function (e) {
self.onMouseLeave(e);
};
nameEl.bind("mouseenter", data, enterClosure);
numbEl.bind("mouseenter", data, enterClosure);
nameEl.bind("mouseleave", data, leaveClosure);
numbEl.bind("mouseleave", data, leaveClosure);
}
this.setupArrows = function () {
var dateString = this.monthsOfYear[this.date.getMonth()] + " " + this.date.getFullYear();
var html = "";
html += "<div class=\"timeline_lastyear\" title=\"Previous Year\"></div>"
html += "<div class=\"timeline_lastmonth\" title=\"Previous Month\"></div>"
html += "<div class=\"timeline_date\">" + dateString + "</div>"
html += "<div class=\"timeline_nextmonth\" title=\"Next Month\"></div>"
html += "<div class=\"timeline_nextyear\" title=\"Next Year\"></div>"
this.placeHolders.arrows.append(html);
var children = this.placeHolders.arrows.children();
var self = this;
$(children[0]).bind("click", this, function () {
self.previousYear()
});
$(children[1]).bind("click", this, function () {
self.previousMonth()
});
$(children[3]).bind("click", this, function () {
self.nextMonth()
});
$(children[4]).bind("click", this, function () {
self.nextYear()
});
}
this.getEventsForDay = function (dayNumber) {
var result = [];
for (var i = 0; i < this.events.length; i++) {
var e = this.events[i];
if (e.day == dayNumber && e.month == this.date.getMonth() && e.year == this.date.getFullYear()) result.push(this.events[i]);
}
return result;
}
this.setupPlaceHolders = function () {
var arrows = jQuery(document.createElement("div"));
arrows.addClass("timeline_arrows");
var bottom = jQuery(document.createElement("div"));
bottom.addClass("timeline_bottom");
var top = jQuery(document.createElement("div"));
top.addClass("timeline_top");
top.append("<ul></ul>");
bottom.append("<ul></ul>");
this.container.append([arrows[0], top[0], bottom[0]]);
return {
arrows: arrows,
bottom: bottom.find("ul:first"),
top: top.find("ul:first")
};
}
this.getMonthRepresentation = function () {
var result = [];
var numberOfDays = this.getNumberOfDaysInMonth(this.date);
var firstDay = this.getFirstDayOfMonth(this.date);
var finished = false;
for (var i = 0; i < numberOfDays; i++) {
result.push({
name: this.weekDays[firstDay].substring(0, 3),
number: (i + 1 < 10) ? "0" + (i + 1) : (i + 1),
events: this.getEventsForDay(i + 1)
});
firstDay = (firstDay == 6) ? 0 : ++firstDay;
}
return result;
}
this.getNumberOfDaysInMonth = function (dateObject) {
var month = dateObject.getMonth();
if (month == 1) {
var leapYear = (new Date(dateObject.getYear(), 1, 29).getDate()) == 29;
if (leapYear) return 29
else return 28;
} else return this.daysPerMonth[month];
},
this.getFirstDayOfMonth = function (dateObject) {
var save = dateObject.getDate();
dateObject.setDate(1);
var result = dateObject.getDay();
dateObject.setDate(save);
return result;
},
this.isToday = function (dayNumber) {
var today = new Date();
return (today.getDate() == dayNumber && today.getFullYear() == this.date.getFullYear() && today.getMonth() == this.date.getMonth());
},
this.onMouseEnter = function (event) {
var left = $(event.target).offset().left;
var width = $(event.target).outerWidth();
this.bubble.setContent(event.data.events);
this.bubble.show(left + (width / 2));
}
this.onMouseLeave = function (event) {
this.bubble.hide();
}
this.nextMonth = function () {
this.date.setMonth(this.date.getMonth() + 1);
this.render();
}
this.nextYear = function () {
this.date.setYear(this.date.getFullYear() + 1);
this.render();
}
this.previousMonth = function () {
this.date.setMonth(this.date.getMonth() - 1);
this.render();
}
this.previousYear = function () {
this.date.setYear(this.date.getFullYear() - 1);
this.render();
}
this.initialize();
}
Timeline.Bubble = function (timeline) {
this.initialize = function () {
var IE6Class = (timeline.isIE6) ? " bubbleIE6" : "";
var id = "bubble_" + new Date().getTime();
var html = "";
html += "<div id=\"" + id + "\" class=\"timeline_bubble\">";
html += "<div class=\"bubble_top" + IE6Class + "\"></div>";
html += "<div class=\"bubble_mid" + IE6Class + "\"></div>";
html += "<div class=\"bubble_bottom" + IE6Class + "\"></div></div>";
timeline.container.after(html);
this.container = $("#" + id);
this.container.bind("mouseenter", this, this.onMouseEnter);
this.container.bind("mouseleave", this, this.onMouseLeave);
}
this.onMouseEnter = function (event) {
event.data.stopHiding();
}
this.onMouseLeave = function (event) {
event.data.hide();
}
this.stopHiding = function () {
if (this.goingOffHandle && this.goingOffHandle != null) {
clearTimeout(this.goingOffHandle);
this.goingOffHandle = null;
}
}
this.setContent = function (events) {
this.stopHiding();
var html = "";
for (var i = 0; i < events.length; i++)
html += "<div><div class=\"event_title\">" + events[i].name + "<p class=\"event_data\">" + events[i].content + "</p></div></div>";
var midSection = $(this.container.children()[1]);
midSection.empty();
midSection.append(html);
var titles = midSection.find(".event_title");
titles.each(function (inx, element) {
$(element).bind("mouseenter", function (event) {
$(element).children(":first").animate({
opacity: "toggle"
}, 200);
});
$(element).bind("mouseleave", function (event) {
$(element).children(":first").animate({
opacity: "hide"
}, 200);
});
});
}
this.show = function (at) {
this.container.animate({
opacity: "show"
}, 250);
this.container.animate({
left: at - (this.container.outerWidth() / 2)
}, 300);
}
this.hide = function () {
var self = this;
this.goingOffHandle = setTimeout(function () {
self.container.animate({
opacity: "hide"
}, 250);
}, 700);
}
this.initialize();
}
In this.renderDay try inverting the two .append lines :
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
so that it reads
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");

Categories