Related
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 :)
So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.
setScreen('LogIn');
var balance;
var curbal = [];
var totalAccts=[];
onEvent("saveAcct", "click", function() {
var username = getText('createUserInput');
var password = getText('createPassInput');
appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
console.log("Username: " + username + " Password: " + password);
console.log(totalAccts);
setScreen('LogIn');
});
onEvent('makeAcct', 'click', function(){
setScreen('CreateAcct');
setText('createUserInput', "");
setText('createPassInput', "");
setText("userInput", "");
setText("passInput", "");
hideElement('alert');
});
onEvent('addMoney', 'click', function(){
setNumber('balance', balance + getNumber('addInput'));
balance = balance + getNumber('addInput');
setNumber('addInput', '');
console.log(balance);
});
onEvent('subMoney', 'click', function(){
setNumber('balance', balance - getNumber('subInput'));
balance = balance - getNumber('subInput');
setNumber('subInput', '');
console.log(balance);
});
onEvent('login', 'click', function(){
balance = 0;
changeEnBal(totalAccts, curbal);
});
onEvent('logout', 'click', function(){
changeExBal(totalAccts, getNumber('balance'), curbal);
hideElement('alert');
setText('balance', 0);
setText("userInput", "");
setText("passInput", "");
setScreen('LogIn');
});
onEvent("goBack", "click", function() {
setScreen('LogIn');
});
function changeEnBal(list, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
setScreen('Account');
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balance = balList[a];
setNumber('balance', balList[a]);
setScreen('Account');
console.log(balList[a]);
}
}
}
}
for (var b = 0; b < balList.length; b++) {
if (balList[b] != (user + " " + pass + " " + balList[b])){
showElement('alert');
}
}
}
function changeExBal(list, curBal, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
list[i] = user + " " + pass + " " + curBal;
appendItem(curbal, curBal);
console.log(curbal);
console.log(list[i]);
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balList[a] = curbal;
list[i] = user + " " + pass + " " + curBal;
}
}
}
}
console.log(totalAccts);
}
As suggested in some of the comments I would change your for loops to start with a zero index:
for (var i = 0; i < list.length; i++)
and
for (var a = 0; a < balList.length; a++)
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.
I can't figure out why this snippet logs false. I'm convinced it should log to true. What am I doing wrong?
var hasElb = function(string12b,char12b) {
var el = [];
for (var i = 0; i < string12b.length; i++ ) {
if (string12b[i] === char12b) {
el += char12b;
}
}
if (el[0] === char12b) {
console.log(true + " el[0] = " + el[0] + " and char12b = " + char12b);
}
else {
console.log(false + " el[0] = " + el[0] + " and char12b = " + char12b);
}
};
hasElb([1,3,5,7,9,11],7);
To add an element to an array, you use .push(), not +=:
if (string12b[i] === char12b) {
el.push(char12b);
}
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();
});