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 :)
Here is the problem:
Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
PC,
Collors,
offer = "Offers: " + "\n";
for (var i = 0; i < pcs.length; i++) {
PC = pcs[i];
Collors = Object.keys(PC.color);
if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {
for ( var j = 0; j < Collors.length; j++) {
if ((PC.color.black >= 2) && (PC.color.white >= 2)) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
}
else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
}
}
}
console.log(offer);
Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?
Many thanks for all help,
You loop over Collors. For acer both black and white have >2. So the first rule that checks black and white matches once for black and once for white.
A solution is to not loop over Collors at all but check black and white separately directly:
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"melyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
PC,
Collors,
offer = [],
colors;
for (var i = 0; i < pcs.length; i++) {
colors = [];
PC = pcs[i];
if (PC.color.black >= 2) {
colors.push("black");
}
if (PC.color.white >= 2) {
colors.push("white");
}
if (PC.price * 2 <= 1600 && colors.length > 0) {
offer.push({
"model": PC.model,
"total price": PC.price * 2,
"color": colors
});
}
}
console.log(JSON.stringify(offer, undefined, "\t"));
Code to solve problem to get required output in console.
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
];
for (var i=0; i < pcs.length; i++) {
if((pcs[i].color.black >=2 || pcs[i].color.white >=2) && pcs[i].price *2 <=1600){
//console.log (pcs[i]);
var colors = Object.keys(pcs[i].color),
color = '';
for(var j = 0; j < colors.length; j++){
if ((pcs[i].color.black >= 2 && colors[j] === "black") ||
(pcs[i].color.white >= 2 && colors[j] === "white" )) {
if (color.length > 0) {
color += ' and ' + colors[j];
} else {
color = colors[j];
}
}
}
console.log('Model: ' + pcs[i].model + '\nPrice: ' + pcs[i].price*2 + '\nSpalvos: ' + color);
}
}
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.
In the below code, initially as the page is loading, complete block is executed. But after the page is loaded, only the else condition is getting executed.why?
Please find below complete piece of code.
unction verifyrequestArray(id) {
console.log("in verifyrequestarray" + requestArray.length);
var y = true;
//requestArray=["1012-abc","2089-xyz","1012-abc"];
var tempArr = [];
//for removing duplicates in the array
for (i = 0; i < requestArray.length; i++) {
if (tempArr.indexOf(requestArray[i]) == -1) {
tempArr.push(requestArray[i]);
}
}
//alert(tempArr);
//verify if the value already exists
for (j = 0; j < tempArr.length; j++) {
if (tempArr.hasOwnProperty(id)) {
console.log("req id already present in array");
break;
} else {
console.log("req id not present in array");
return false;
}
}
}
function getStatusfromArray(id) {
console.log("in get status");
requestStatus = requestArray.hasOwnProperty(id);
console.log("status for " + id + ":" + requestStatus);
return requestStatus;
}
function setTooltip(currentTag, status) {
console.log("in settooltip" + currentTag);
currentTag.attr("title", status); //setting status a tooltip
}
function getStatusUsingAjax(requestValue, callback) {
console.log("inside function getStatusUsingAjax");
var currentStatus;
GM_xmlhttpRequest({
method: "GET",
url: link,
async: false,
onload: function(response) {
if ($(response.responseText).find("#P16_STATUS2").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS2").text();
console.log("Status is " + currentStatus);
} else if ($(response.responseText).find("#P16_STATUS3").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS3").val();
console.log("Status is " + currentStatus);
}
var pusharr2 = [requestValue + "-" + currentStatus];
requestArray.push(pusharr2);
//console.log("Updated Array is "+requestArray);
callback(currentStatus);
}
});
}
function loadStatus(x) {
$('.a-IRR-table tr').each(function(i) {
var val = $(this).find("td").eq(0).text();
if ((val !== "-") && (val !== "")) {
link = $(this).find("td").eq(0).find("a").attr("href");
linkTag = $(this).find("td").eq(0).find("a");
console.log("Link Tag is " + linkTag);
console.log("val is " + val);
var x = verifyrequestArray(val);
console.log("x is " + x);
if (verifyrequestArray(val)) {
var updatedStatus = getStatusfromArray(val);
setTooltip(linkTag, updatedStatus);
} else {
console.log("in else");
//var updatedStatus2=getStatusUsingAjax(val);
getStatusUsingAjax(val, function(updatedStatus2) {
console.log("UpdatedStatus2 is " + updatedStatus2);
console.log("Link Tag is " + linkTag);
setTooltip(linkTag, updatedStatus2);
});
sleep(1.5 * 1000);
}
}
});
}
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>");