Javascript Hanging UI on IE6/7 - javascript

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!

This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Related

How to iterate a JavaScript code for two objects

I would like to apply same piece of code to two objects in JavaScript.
When calling getElementsByClass ,there appears 2 objects in my website.So I would like to apply the same code for both of them.Currently I'm applying it to only one Object (text[0]) and I would like to implement it also to text[1] .
var text=document.getElementsByClassName("th");
var text =text[0];
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
I think you want to do the same thing with using item[0] and item[1] together.
You can create a function. Or call this function by iterating your items too.
var text=document.getElementsByClassName("th");
function myFunc(text) {
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
}
myFunc(text[0]); // call functions with your items.
myFunc(text[1]);

how to fix if .media$thumbnail.url not found?

I'm Building a widget for blogger
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postSummary = json.feed.entry[i].summary.$t;
var Thumb = json.feed.entry[i].media$thumbnail.url;
var item = '<div class="wrapper"><img src='+ Thumb +' /><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><p>' + postSummary + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://smag-soratemplates.blogspot.com/feeds/posts/summary?max-results=5&alt=json-in-script&callback=mycallback"></script>
but if there is no image in the post or cant find .media$thumbnail.url
the widget stops working , anyone know how to fix that ? or to show an alternative image?
sorry i'm a beginner
If it's failing when the thumbnail does not exist, then you can put a check for the thumbnail
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postSummary = json.feed.entry[i].summary.$t;
var Thumb = json.feed.entry[i].media$thumbnail.url;
if( typeof Thumb == "undefined" ) {
Thumb = '/Your custom image url';
}
var item = '<div class="wrapper"><img src='+ Thumb +' /><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><p>' + postSummary + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://smag-soratemplates.blogspot.com/feeds/posts/summary?max-results=5&alt=json-in-script&callback=mycallback"></script>
You need to use or(||) in the Thumb definition like that
var Thumb = json.feed.entry[i].media$thumbnail.url || 'https://i.imgur.com/5WMAvAu.gif';
Here, if json.feed.entry[i].media$thumbnail.url is undefine/false/null, Thumb is set to 'https://i.imgur.com/5WMAvAu.gif' as your default image.
You need to check that all of the values are present:
json.feed.entry[i].media$thumbnail.url
as any of these items could be null / undefined:
json
json.feed
json.feed.entry[i]
json.feed.entry[i].media$thumbnail
json.feed.entry[i].media$thumbnail.url
At the least, you should check:
if(json.feed.entry[i].media$thumbnail && json.feed.entry[i].media$thumbnail.url)
Also, it's probably worth rewriting this code as follows:
let entry = json.feed.entry[i];
to save yourself some typing (and to stop all the object look ups each time when using dots to reference nested objects).
The code then becomes:
let url = '';
if (entry.media$thumbnail && media$thumbnail.url) {
url = entry.media$thumbnail.url;
}
else {
url = 'the default image URL';
}
Thank you all i found the solution
by replacing this code
var Thumb = json.feed.entry[i].media$thumbnail.url;
with this code
if (json.feed.entry[i].media$thumbnail)
{
Thumb = json.feed.entry[i].media$thumbnail.url;
}
else
{
Thumb= "'Image url'";
}

Thumbnail not show on related post blogger [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I use blogger costum domain. Related post image thumbnail not show on the detail post (example this post). Image was upload (cache) on my subdomain.
this script on related post
<script>
//<![CDATA[
var related_blogUrl = "https://www.perantiguru.com";
var related_total = 6;
var related_thumbnail = 1;
var related_imgWidth = 210;
var related_imgHeight = 130;
(function(){
var relatedNum = 0; var relatedUrl = new Array(); var relatedImage = new Array(); var relatedTitle = new Array(); var relatedTotal = related_total; var callback = "relatedposts"; var containerID = document.getElementById("relatedposts"); var noImg = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"; var imgSize = [related_imgWidth, related_imgHeight]; window[callback] = function(data){ for (var i = 0; i < data.feed.entry.length; i++){ var entry = data.feed.entry[i]; relatedTitle[relatedNum] = entry.title.$t; for (var j = 0; j < entry.link.length; j++){ if ("alternate" == entry.link[j].rel){ relatedUrl[relatedNum] = entry.link[j].href; break; } } relatedImage[relatedNum] = noImg.replace("/s72-c/", "/w" + imgSize[0] + "-h" + imgSize[1] + "-p-k-no-nu/"); if ("media$thumbnail" in entry) { relatedImage[relatedNum] = entry.media$thumbnail.url.replace("/s72-c/", "/w"+imgSize[0]+"-h"+imgSize[1]+"-p-k-no-nu/"); } relatedNum++; } }; function filterTags(g, h) { var e = g.split("<"); for (var f = 0; f < e.length; f++) { if (e[f].indexOf(">") != -1) { e[f] = e[f].substring(e[f].indexOf(">") + 1, e[f].length) } } e = e.join(""); e = e.substring(0, h - 1); return e; }; function contains(a, e) { for (var f = 0; f < a.length; f++) { if (a[f] == e) return true; } return false; }; function removeDuplicates() { var v = new Array(0); var A = new Array(0); var w = new Array(0); for (var u = 0; u < relatedUrl.length; u++) { if (!contains(v, relatedUrl[u])) { v.length += 1; v[v.length - 1] = relatedUrl[u]; A.length += 1; A[A.length - 1] = relatedImage[u]; w.length += 1; w[w.length - 1] = relatedTitle[u]; } } relatedUrl = v; relatedImage = A; relatedTitle = w; }; function createRelated() { removeDuplicates(); for (var u = 0; u < relatedTitle.length; u++) { var B = Math.floor((relatedTitle.length - 1) * Math.random()); var s = relatedUrl[u]; var C = relatedImage[u]; var i = relatedTitle[u]; relatedUrl[u] = relatedUrl[B]; relatedImage[u] = relatedImage[B]; relatedTitle[u] = relatedTitle[B]; relatedUrl[B] = s; relatedImage[B] = C; relatedTitle[B] = i; } var r = 0; var D = Math.floor((relatedTitle.length - 1) * Math.random()); var z = D; var t = document.URL; var e = ""; while (r < relatedTotal) { if (relatedUrl[D] != t) { e += "<li>"; if (related_thumbnail >= 1) { e += "<div class='thumbnail'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>"; e += "<img src='" + relatedImage[D] + "' alt='" + relatedTitle[D] + "' width='" + imgSize[0] +"' height='" + imgSize[1] + "'/>"; e += "</a>"; e += "</div>"; } e += "<div class='title'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>" + relatedTitle[D] + "</a>"; e += "</div>"; e += "</li>"; r++; if (r == relatedTotal) { break; } } if (D < relatedTitle.length - 1) { D++; } else { D = 0; } if (D == z) { break; } } containerID.innerHTML = e; }; var labels = ""; var ralatedlist = document.querySelectorAll("span.list-item"); ralatedlist.forEach(function(list) { labels += 'label:"' + list.dataset.label + '"|'; }); var js = document.createElement("script"); var blogUrl = related_blogUrl.replace(/\/$/, ""); js.src = blogUrl + "/feeds/posts/summary?v=2&q=" + labels + "&alt=json&callback=" + callback + "&max-results=20"; js.onload = createRelated; document.getElementsByTagName("head")[0].appendChild(js);
})();
//]]>
</script>
help me to fix it
fixed, Thumbnail not show on related post blogger from external source
Before:
<b:if cond='data:blog.pageType == "item"'>
<div class='relatedposts'>
<h4>Post Lainnya</h4>
<ul id='relatedposts'>
<b:loop values='data:post.labels' var='label'>
<span class='list-item' expr:data-label='data:label.name'/>
</b:loop>
</ul>
</div>
</b:if>
<script>
//<![CDATA[
var related_blogUrl = "https://www.perantiguru.com";
var related_total = 6;
var related_thumbnail = 1;
var related_imgWidth = 210;
var related_imgHeight = 130;
(function(){
var relatedNum = 0; var relatedUrl = new Array(); var relatedImage = new Array(); var relatedTitle = new Array(); var relatedTotal = related_total; var callback = "relatedposts"; var containerID = document.getElementById("relatedposts"); var noImg = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"; var imgSize = [related_imgWidth, related_imgHeight]; window[callback] = function(data){ for (var i = 0; i < data.feed.entry.length; i++){ var entry = data.feed.entry[i]; relatedTitle[relatedNum] = entry.title.$t; for (var j = 0; j < entry.link.length; j++){ if ("alternate" == entry.link[j].rel){ relatedUrl[relatedNum] = entry.link[j].href; break; } } relatedImage[relatedNum] = noImg.replace("/s72-c/", "/w" + imgSize[0] + "-h" + imgSize[1] + "-p-k-no-nu/"); if ("media$thumbnail" in entry) { relatedImage[relatedNum] = entry.media$thumbnail.url.replace("/s72-c/", "/w"+imgSize[0]+"-h"+imgSize[1]+"-p-k-no-nu/"); } relatedNum++; } }; function filterTags(g, h) { var e = g.split("<"); for (var f = 0; f < e.length; f++) { if (e[f].indexOf(">") != -1) { e[f] = e[f].substring(e[f].indexOf(">") + 1, e[f].length) } } e = e.join(""); e = e.substring(0, h - 1); return e; }; function contains(a, e) { for (var f = 0; f < a.length; f++) { if (a[f] == e) return true; } return false; }; function removeDuplicates() { var v = new Array(0); var A = new Array(0); var w = new Array(0); for (var u = 0; u < relatedUrl.length; u++) { if (!contains(v, relatedUrl[u])) { v.length += 1; v[v.length - 1] = relatedUrl[u]; A.length += 1; A[A.length - 1] = relatedImage[u]; w.length += 1; w[w.length - 1] = relatedTitle[u]; } } relatedUrl = v; relatedImage = A; relatedTitle = w; }; function createRelated() { removeDuplicates(); for (var u = 0; u < relatedTitle.length; u++) { var B = Math.floor((relatedTitle.length - 1) * Math.random()); var s = relatedUrl[u]; var C = relatedImage[u]; var i = relatedTitle[u]; relatedUrl[u] = relatedUrl[B]; relatedImage[u] = relatedImage[B]; relatedTitle[u] = relatedTitle[B]; relatedUrl[B] = s; relatedImage[B] = C; relatedTitle[B] = i; } var r = 0; var D = Math.floor((relatedTitle.length - 1) * Math.random()); var z = D; var t = document.URL; var e = ""; while (r < relatedTotal) { if (relatedUrl[D] != t) { e += "<li>"; if (related_thumbnail >= 1) { e += "<div class='thumbnail'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>"; e += "<img src='" + relatedImage[D] + "' alt='" + relatedTitle[D] + "' width='" + imgSize[0] +"' height='" + imgSize[1] + "'/>"; e += "</a>"; e += "</div>"; } e += "<div class='title'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>" + relatedTitle[D] + "</a>"; e += "</div>"; e += "</li>"; r++; if (r == relatedTotal) { break; } } if (D < relatedTitle.length - 1) { D++; } else { D = 0; } if (D == z) { break; } } containerID.innerHTML = e; }; var labels = ""; var ralatedlist = document.querySelectorAll("span.list-item"); ralatedlist.forEach(function(list) { labels += 'label:"' + list.dataset.label + '"|'; }); var js = document.createElement("script"); var blogUrl = related_blogUrl.replace(/\/$/, ""); js.src = blogUrl + "/feeds/posts/summary?v=2&q=" + labels + "&alt=json&callback=" + callback + "&max-results=20"; js.onload = createRelated; document.getElementsByTagName("head")[0].appendChild(js);
})();
//]]>
</script>
After:
<b:if cond='data:blog.pageType == "item"'>
<div id='related-posts'>
<b:loop index='labelcount' values='data:post.labels' var='label'>
<script>
var currentURL = '<data:blog.url/>';
</script>
<b:if cond='data:labelcount < 1'>
<script async='async' expr:src='"/feeds/posts/default/-/" + data:label.name + "?alt=json-in-script&callback=display_related_posts"' type='text/javascript'/></b:if></b:loop>
</div><div style='clear:both'/>
</b:if>
<script type='text/javascript'>
/*<![CDATA[*/
var post_thumbnail_width = 180;
var post_thumbnail_height = 120;
var max_related_entries = 6;
function escapeRegExp(string){return string.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function replaceAll(str,term,replacement){return str.replace(new RegExp(escapeRegExp(term),"g"),replacement)}function display_related_posts(json_feed){for(var defaultnoimage="https://i.ibb.co/yS6JvBh/no-image.jpg",post_titles=new Array,title_num=0,post_urls=new Array,post_thumbnail_url=new Array,relatedpoststitle=(window.location.href,"Post Lainnya"),border_color="#DDDDDD",i=0;i<json_feed.feed.entry.length;i++){var feed_entry=json_feed.feed.entry[i];post_titles[title_num]=feed_entry.title.$t;try{post_thumbnail_url[title_num]=feed_entry.media$thumbnail.url}catch(error){s=feed_entry.content.$t,a=s.indexOf("<img"),b=s.indexOf('src="',a),c=s.indexOf('"',b+5),d=s.substr(b+5,c-b-5),-1!=a&&-1!=b&&-1!=c&&""!=d?post_thumbnail_url[title_num]=d:"undefined"!=typeof defaultnoimage?post_thumbnail_url[title_num]=defaultnoimage:post_thumbnail_url[title_num]="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"}for(var k=0;k<feed_entry.link.length;k++)"alternate"==feed_entry.link[k].rel&&(post_urls[title_num]=feed_entry.link[k].href,title_num++)}var random_entry=Math.floor((post_titles.length-1)*Math.random()),iteration=0;if(post_titles.length>0){var rp_heading=document.createElement("h2"),textnode=document.createTextNode(relatedpoststitle);rp_heading.appendChild(textnode),document.getElementById("related-posts").appendChild(rp_heading);var rp_container=document.createElement("div");rp_container.setAttribute("style","clear: both;"),rp_container.setAttribute("id","rp-container"),document.getElementById("related-posts").appendChild(rp_container)}for(;iteration<post_titles.length&&20>iteration&&max_related_entries>iteration;)if(post_urls[random_entry]!=currentURL){var rp_anchor=document.createElement("a");0!=iteration?rp_anchor.setAttribute("style","text-decoration:none;padding:10px;float:left;border-left: none "+border_color+";"):rp_anchor.setAttribute("style","text-decoration:none;padding:10px;float:left;"),rp_anchor.setAttribute("id","rp-anchor-"+iteration),rp_anchor.setAttribute("href",post_urls[random_entry]),document.getElementById("rp-container").appendChild(rp_anchor);var rp_img=document.createElement("img");rp_img.setAttribute("style","width:"+post_thumbnail_width+"px;height:"+post_thumbnail_height+"px; border:1px solid #CCCCCC;"),rp_img.setAttribute("id","rp-img-"+iteration);var pin=String(post_thumbnail_url[random_entry].match(/\/s72-c\//));post_thumbnail_url[random_entry]=replaceAll(post_thumbnail_url[random_entry],pin,"/w"+post_thumbnail_width+"-h"+post_thumbnail_height+"-p/"),rp_img.setAttribute("src",post_thumbnail_url[random_entry]),rp_img.setAttribute("alt","Matched post excerpt thumbnail in the post footer."),document.getElementById("rp-anchor-"+iteration).appendChild(rp_img);var rp_para=document.createElement("div");rp_para.setAttribute("style","width:"+post_thumbnail_width+"px; height:"+post_thumbnail_height+"px;border: 0pt none ; margin: auto; padding-top: 18px; line-height:1.6;"),rp_para.setAttribute("id","rp-para-"+iteration);var textnode=document.createTextNode(post_titles[random_entry]);rp_para.appendChild(textnode),document.getElementById("rp-anchor-"+iteration).appendChild(rp_para),iteration++,random_entry<post_titles.length-1?random_entry++:random_entry=0}else iteration++,random_entry<post_titles.length-1?random_entry++:random_entry=0;post_urls.splice(0,post_urls.length),post_thumbnail_url.splice(0,post_thumbnail_url.length),post_titles.splice(0,post_titles.length)}
/*]]>*/
</script>

Identify the first and last two posts

I am using the script below to show the latest 5 posts on my Blogger blog. How can I wrap the first and last 2 posts in different div containers? Currently all the 5 posts are inside a wrapper container stored in the item variable:
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>
More generic solution would not check for last and previous to last elements checking for 3 or 4 but should be based on total length of your posts (it can be 3 it can be 10000).
Checks below should be place in your loop.
if(i === 0 || i === 1)
Always use === operator as it is typesafe.
Also group your checks in a way that is easy to understand (check for first and second in one if and for last and previous to last in another if:
if(i === json.feed.entry.length || i === json.feed.entry.length - 1) - this check is based on length of your entries, not some fixed value like 3 or 4.
This way if your displayed entries value will change in future (to ex. 10), you don't need to adjust your code here. All code you write should strive to work without such adjustments when code it uses changes.
Check desired elements through loop
// to check first or fourth element
if (i == 0 || i == 3)
// to check second or fifth element
if (i == 1 || i == 4)
Wrap them by adding HTML tages
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
if (i == 0 || i == 3) document.write('<div>');
document.write(item);
if (i == 1 || i == 4) document.write('</div>');
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>

Multiple Group By using two look-up columns which have multi valued selection enabled on an SP 2013 list using JavaScript

So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>    -    AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.

Categories

Resources