blade pagination start data page 0 label 1 using jquery - javascript

I'm using blade pagination for my project.
The pagination is working fine.
Now I want to make like,
The data-page should start from 0,1,2,3... And the label should
starts from 1,2,3,4...
Jquery script
$.fn.bladePagination = function(options) {
if(typeof(options) === 'object' || typeof(options) === 'undefined') {
var settings = $.extend({}, $.fn.bladePagination.defaults, options);
return this.each(function() {
var jqPagination = $(this);
if(jqPagination.hasClass('slice-pagination')) {
createPagination(jqPagination, settings);
initPageClick(jqPagination, settings);
}
});
}
};
/*==============================================
* default options
*==============================================
*/
$.fn.bladePagination.defaults = {
maxPageNum: 5,
firstLabel: '|<', // |<
prevLabel: '<', // <
nextLabel: '>', // >
lastLabel: '>|', // >|
moreLabel: '...',
rebuildAfterClick: false,
clickPage: function(page, jqPagination) {}
};
/*==============================================
* private functions
*==============================================
*/
var createPagination = function(jqPagination, settings) {
var currPage = Number(jqPagination.attr('data-current'));
var totalPage = Number(jqPagination.attr('data-total'));
var pageShowArray = new Array();
//first page number changed into zero
pageShowArray.push({
type: 'page first' + ((1 == currPage) ? ' disabled' : '')
, page: 1
, show: settings.firstLabel
});
//previous page
pageShowArray.push({
type: 'page prev' + ((1 == currPage) ? ' disabled' : '')
, page: (currPage <= 1) ? 1 : (currPage - 1)
, show: settings.prevLabel
});
//page number
var pageNumArray = new Array();
var leftPageNum = (settings.maxPageNum - 1) / 2;
var rightPageNum = settings.maxPageNum - 1 - leftPageNum;
if(currPage - leftPageNum < 1) {
for(var i = leftPageNum; i > 0; i --) {
var page = currPage - i;
if(page < 1) {
rightPageNum ++;
} else {
pageNumArray.push(page);
}
}
pageNumArray.push(currPage);
for(var i = 1; i <= rightPageNum; i ++) {
var page = currPage + i;
if(page > totalPage) break;
pageNumArray.push(page);
}
} else {
for(var i = rightPageNum; i > 0; i --) {
var page = currPage + i;
if(page > totalPage) {
leftPageNum ++;
} else {
pageNumArray.unshift(page);
}
}
pageNumArray.unshift(currPage);
for(var i = 1; i <= leftPageNum; i ++) {
var page = currPage - i;
if(page < 1) break;
pageNumArray.unshift(page);
}
}
if(pageNumArray[0] > 1) {
pageShowArray.push({
type: 'more'
, page: -1
, show: settings.moreLabel
});
}
for(var i = 0; i < pageNumArray.length; i ++) {
var pageNum = pageNumArray[i];
pageShowArray.push({
type: 'page' + ((pageNum == currPage) ? ' active' : '')
, page: pageNum
, show: pageNum
});
}
if(pageNumArray[pageNumArray.length - 1] < totalPage) {
pageShowArray.push({
type: 'more'
, page: -1
, show: settings.moreLabel
});
}
//next page
pageShowArray.push({
type: 'page next' + ((totalPage == currPage) ? ' disabled' : '')
, page: (currPage >= totalPage) ? totalPage : (currPage + 1)
, show: settings.nextLabel
});
//last page
pageShowArray.push({
type: 'page last' + ((totalPage == currPage) ? ' disabled' : '')
, page: totalPage
, show: settings.lastLabel
});
//create page
jqPagination.empty();
for(var i = 0; i < pageShowArray.length; i ++) {
var pageShow = pageShowArray[i];
var html = '<li class="' + pageShow.type + '" data-page="' + pageShow.page + '">' + pageShow.show + '</li>';
jqPagination.append(html);
}
}
var initPageClick = function(jqPagination, settings) {
var jqPageSet = jqPagination.find('li.page');
//event handler
jqPageSet.off('click');
jqPageSet.click(function() {
var jqPage = $(this);
if(! (jqPage.hasClass('active') || jqPage.hasClass('disabled'))) {
var page = jqPage.data('page');
settings.clickPage(page, jqPagination);
if(settings.rebuildAfterClick) {
//rebuild
createPagination(jqPagination, settings);
initPageClick(jqPagination, settings);
}
}
});
}
I want to change something here
var html = '<li class="' + pageShow.type + '" data-page="' + pageShow.page + '">' + pageShow.show + '</li>';
I'm using some other library to get images, there the image value start from 0, In that library i can't able to make changes.
i want like this to start like this below
<li data-page='0'>1</li>
<li data-page='1'>2</li>
<li data-page='2'>3</li>

Try this:
var html = '<li class="' + pageShow.type + '" data-page="' + pageShow.page + '">' + (parseInt(pageShow.page)+1) + '</li>';
May be it will work for you.

Related

Object.defineProperty called on non-object error

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 :)

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.

Sum of value in label having same class

I am trying to add all values of class tmpcpa and place result in final_cpa but final_cpa always return 0.
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
Surprisingly when i view source code in browser HTML appears as
<label class="tmpcpa">0</label> but when i do inspect element it shows as
<label class="tmpcpa">30.0</label>
Update here is the whole JS. HTML calls process function which ultimately calls calculate_final_cpa()
//"use strict";
function process(arr) {
document.getElementById('txtgrade' + arr[0] + arr[1] + arr[2]).innerHTML = show_grade(document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value);
if (validateForm(arr)) {
var module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value;
var module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + arr[2]).innerHTML;
if (!isNaN(module_percentage) || !isNaN(module_credit)) {
module_percentage = 0;
module_credit = 0;
var total_credit_semester = 0;
var sum_module_percentage_x_credit = 0;
for ( i= 2 ; i <= arr[3] + 1 ; i++) {
module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + i).value;
module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + i).innerHTML;
sum_module_percentage_x_credit += module_percentage * module_credit;
total_credit_semester += module_credit;
}
//console.log(module_percentage);
var spa = sum_module_percentage_x_credit / total_credit_semester;
spa = spa.toFixed(1);
document.getElementById('spa' + arr[0] + arr[1]).innerHTML = spa;
calculate_cpa(arr);
}
}
}
function validateForm(arr) {
var isValid = true;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' :input').each(function () {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
/*
* Works for 2 semester per level and 3 year course (optimize later)
*/
function calculate_cpa(arr) {
var isValid = true;
for ( i= 1 ; i <= 2 ; i++) {
var spa = document.getElementById('spa' + arr[0] + i).innerHTML;
if (spa == "N/A") {
isValid = false;
}
}
if (isValid) {
var total_credit_level = 0;
var total_spa_x_credit = 0;
for ( i= 1 ; i <= 2 ; i++) {
var arr2= [arr[0], i];
var spa = +document.getElementById('spa' + arr[0] + i).innerHTML;
total_spa_x_credit += spa * getcredits(arr2);
total_credit_level += getcredits(arr2);
}
var cpa = total_spa_x_credit / total_credit_level;
cpa = cpa.toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa;
var level = +document.getElementById('level' + arr[0]).innerHTML
var tmp_cpa = ((level / 100) * cpa).toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label class="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
if (final_cpa != 0) {
var award = show_award(final_cpa);
document.getElementById('award').innerHTML = award;
document.getElementById('finalcpa').innerHTML = final_cpa;
}
}
}
function getcredits(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
function show_grade(module_percentage) {
if (isNaN(module_percentage)) {
return 'N/A';
}
if (module_percentage >= 70 && module_percentage <= 100) {
return 'A';
} else if (module_percentage >= 60 && module_percentage < 70) {
return 'B';
} else if (module_percentage >= 50 && module_percentage < 60) {
return 'C';
} else if (module_percentage >= 40 && module_percentage < 50) {
return 'D';
} else {
return 'F';
}
}
function show_award(cpa) {
if (isNaN(cpa)) {
return 'N/A';
}
if (cpa >= 70 && cpa <= 100) {
return 'First Class with Honours';
} else if (cpa >= 60 && cpa < 70) {
return 'Second Class First Division with Honours';
} else if (cpa >= 50 && cpa < 60) {
return 'Second Class Second Division with Honours';
} else if (cpa >= 45 && cpa < 50) {
return 'Third Class with Honours';
} else if (cpa >= 40 && cpa < 45) {
return 'Pass';
} else if (cpa < 40) {
return 'No award';
}
}
you need to be sure you are calling the function after the document is ready.
Also, you are using unassigned value.
</body>
<script>
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
$(document).ready(function(){
var final_cpa = calculate_final_cpa();
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + final_cpa + "</label>" +' For Final' + ')';
console.log(final_cpa);
});
</script>

Add fade effect in JavaScript rotation image script

How can I add a fade effect in this javascript?
I try to make fade or slide effect in this script but not working.
my idea is made slideshow effect in my wordpress page. i don't want use plugin because my page is very slow and a try to make very optimized with this javascript
var ultimateshow = new Array()
//ultimateshow[x]=["#", "OPTIONAL link for image", "OPTIONAL link target"]
ultimateshow[0] = ['image1.jpg', '#']
ultimateshow[1] = ['image2.jpg', '#']
var slidewidth = "980px" // width
var slideheight = "250px" // height
var slidecycles = "2" //
var randomorder = "no" //
var preloadimages = "yes" //preload images? "yes" or "no"
var slidebgcolor = 'white'
var slidedelay = 3000
var ie = document.all
var dom = document.getElementById
var curcycle = 0
if (preloadimages == "yes") {
for (i = 0; i < ultimateshow.length; i++) {
var cacheimage = new Image()
cacheimage.src = ultimateshow[i][0]
}
}
var currentslide = 0
function randomize(targetarray) {
ultimateshowCopy = new Array()
var the_one
var z = 0
while (z < targetarray.length) {
the_one = Math.floor(Math.random() * targetarray.length)
if (targetarray[the_one] != "_selected!") {
ultimateshowCopy[z] = targetarray[the_one]
targetarray[the_one] = "_selected!"
z++
}
}
}
if (randomorder == "yes")
randomize(ultimateshow)
else
ultimateshowCopy = ultimateshow
function rotateimages() {
curcycle = (currentslide == 0) ? curcycle + 1 : curcycle
ultcontainer = '<center>'
if (ultimateshowCopy[currentslide][1] != "") ultcontainer += '<a href="' + ultimateshowCopy[currentslide][1] + '" target="' + ultimateshowCopy[currentslide][2] + '">'
ultcontainer += '<img src="' + ultimateshowCopy[currentslide][0] + '" border="0">'
if (ultimateshowCopy[currentslide][1] != "")
ultcontainer += '</a>'
ultcontainer += '</center>'
if (ie || dom)
crossrotateobj.innerHTML = ultcontainer
if (currentslide == ultimateshow.length - 1)
currentslide = 0
else
currentslide++
if (curcycle == parseInt(slidecycles) && currentslide == 0)
return
setTimeout("rotateimages()", slidedelay)
}
if (ie || dom)
document.write('<div id="slidedom" style="width:' + slidewidth + ';height:' + slideheight + '; background-color:' + slidebgcolor + '"></div>')
function start_slider() {
crossrotateobj = dom ? document.getElementById("slidedom") : document.all.slidedom
rotateimages()
}
if (ie || dom)
window.onload = start_slider

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

Categories