document.write() Is Removing All Page Content When Calling After Page Load - javascript

I have a web page where I am reading Google Blogger blog category from his feed using JSON. I have two functions. First on is getting all the Blog Categories List and second one is taking Blog Categories from that and then hitting again Blog to get latest posts from that This is the text test to see that web page data is here or not.
<div id="blogCategoriesList">
<script type="text/javascript">
var blogurl = "https://googleblog.blogspot.com/";
function blogCatList(json) {
document.write('<select onchange="showThisCatPosts(this.value)">');
document.write('<option>CHOOSE A CATEGORY</option>');
for (var i = 0; i < json.feed.category.length; i++)
{
var item = "<option value='" + json.feed.category[i].term + "'>" + json.feed.category[i].term + "</option>";
document.write(item);
}
document.write('</select>');
}
document.write('<script type=\"text/javascript\" src=\"' + blogurl + '/feeds/posts/default?redirect=false&orderby=published&alt=json-in-script&callback=blogCatList&max-results=500\"><\/script>');
document.write('<br/><br/><a href=\"' + blogurl + '\" target=\"_blank\" class=\"footerLINK\">Read The Blog Online Now<\/a>');
</script>
</div>
<div id="blogCategoriesPost">
<script style='text/javascript'>
var blogurl = "https://googleblog.blogspot.com/";
var numposts = 10; // Out Of 500
var displaymore = true;
var showcommentnum = true;
var showpostdate = true;
var showpostsummary = true;
var numchars = 100;
function blogCategoriesPost(json) {
if(json.feed.entry.length < numposts ){
numposts = json.feed.entry.length;
}
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
var commenttext = entry.link[k].title;
var commenturl = entry.link[k].href;
}
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
var postdate = entry.published.$t;
var cdyear = postdate.substring(0, 4);
var cdmonth = postdate.substring(5, 7);
var cdday = postdate.substring(8, 10);
var monthnames = new Array();
monthnames[1] = "Jan";
monthnames[2] = "Feb";
monthnames[3] = "Mar";
monthnames[4] = "Apr";
monthnames[5] = "May";
monthnames[6] = "Jun";
monthnames[7] = "Jul";
monthnames[8] = "Aug";
monthnames[9] = "Sep";
monthnames[10] = "Oct";
monthnames[11] = "Nov";
monthnames[12] = "Dec";
document.write('<div id="mainDIV">');
document.write('<h2 class="post_heading">' + posttitle + '</h2>');
if ("content" in entry) {
var postcontent = entry.content.$t;
} else
if ("summary" in entry) {
var postcontent = entry.summary.$t;
} else var postcontent = "";
var re = /<\S[^>]*>/g;
postcontent = postcontent.replace(re, ""); // Will Show Only Text Instead Of HTML
if (showpostsummary == true) {
if (postcontent.length < numchars) {
document.write('<span class="post_summary">');
document.write(postcontent);
document.write('</span>');
} else {
//document.getElementById("catPosts").innerHTML += '<span class="post_summary">';
document.write('<span class="post_summary">');
postcontent = postcontent.substring(0, numchars);
var quoteEnd = postcontent.lastIndexOf(" ");
postcontent = postcontent.substring(0, quoteEnd);
document.write(postcontent + '...');
document.write('</span>');
}
}
var towrite = '';
document.write('<strong class="post_footer">');
if (showpostdate == true) {
towrite = 'Published On: ' + towrite + monthnames[parseInt(cdmonth, 10)] + '-' + cdday + '-' + cdyear;
}
if (showcommentnum == true) {
if (commenttext == '1 Comments') commenttext = '1 Comment';
if (commenttext == '0 Comments') commenttext = 'No Comments';
commenttext = '<br/>' + commenttext + '';
towrite = towrite + commenttext;
}
if (displaymore == true) {
towrite = towrite + '<br/>Read Full Article -->';
}
document.write(towrite);
document.write('</strong></div>');
}
}
function showThisCatPosts(BLOGCAT){
document.write('<script type=\"text/javascript\" src=\"' + blogurl + '/feeds/posts/default/-/' + BLOGCAT + '?redirect=false&orderby=published&alt=json-in-script&callback=blogCategoriesPost&max-results=500\"><\/script>');
document.write('<a href=\"' + blogurl + '\" target=\"_blank\" class=\"footerLINK\">Read The Blog Online Now<\/a>');
}
</script>
You can see a working DEMO at JSBIN. My problem is that when page load, its works perfectly showing all page data and the blog categories lists too but when I select any category then my all page data remove and only that label posts are visible. Why this is happening...??? I want to just change the posts as per label not to remove all page data...

That's the normal behaviour of document.write(). You might need to use:
document.getElementById("element_id").innerHTML = 'Stuff to Write.';

Finally I got it solved. The reason is that document.write() is bad as it write the text on page load. You can use it if you want to write some text on page load not later.
If you want to write later then have to use document.getElementById("element_id").innerHTML to write your text but if you want to write <script> tags then document.getElementById("element_id").innerHTML is not good as it will write but dont hit the SRC so use document.createElement("script") to write scripts after page load that will be runable too.
See the working DEMO of my code at JSBIN... :)
Special Thanks To: #Praveen Kumar :-)

Related

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'";
}

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.

pagination with different url for each page

i have this .js file for the pagination in html anybody can help me what i have to change to show the different url for each page & user can save that url & can use it for future use to go on that specific page.
(.js file start from below)
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
in this.showPage() update the url hash with something like "pg=1":
location.hash = "#pg=" + pageNumber;
That method will add an item to your page history. If you don't want to add an item to your page history, use this:
location.replace("#pg=" + pageNumber);
Then, when the page is loaded, after you call pager.init(), you'll want to call pager.showPage(). You can use this code to decide whether to load the first page or the page from the url::
var page = /\bpg=(\d+)\b/.test(location.hash) ? parseInt(RegExp.$1) : 1;
pager.showPage(page);

Javascript Hanging UI on IE6/7

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?

Categories

Resources