Thumbnails From External Sources Are Not Appearing In Random Posts Widget - javascript

Here is the jsfiddle for my question.
http://jsfiddle.net/jaribhai/wncwqerj/1/
This is the code.
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("summary" in entry[i]) ? (entry[i].summary.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for(var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
This is the demo of random posts widget from blogger. It is showing thumbnails from only those posts where images are linked from blogger but its not showing thumbnails for those images which are linked from external sources.
What can I do so that images from external hosts also appear in the thumbnails.

As the image is hosted externally , it won't be present in the media$thumbnail field of the feed. We will have to parse the HTML content of the post to extract the URL of the image. Two changes need to be done to make this work -
Firstly switch from the summary feed to default feed URL. This is necessary for getting the HTML content of the post (summary feed only contains the limited summary text of the post not the full HTML). Change every instance of
/feeds/posts/summary?alt=json-in-script
to
/feeds/posts/default?alt=json-in-script
Secondly change the condition for finding the image in the post from
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
to
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
Refer to the working example below -
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length,
j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("content" in entry[i]) ? (entry[i].content.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for (var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
/**
* `document[dot]write` is disallowed in JSFiddle envioriment and might break your fiddle.
*/
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
body {
margin: 0;
padding: 50px;
background-color: white;
font: normal normal 11px/1.4 Arial, Sans-Serif;
color: black;
}
#random-post-container {
width: 400px
}
#random-post-container ul,
#random-post-container li {
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
}
#random-post-container img {
display: block;
float: left;
border: 1px solid;
margin: 2px 7px 5px 0;
}
#random-post-container a {
font-weight: bold;
font-size: 110%;
}
#rancom-post-container .clear {
display: block;
clear: both;
}
<h2>Random Post</h2>
<div id='random-post-container'>Memuat…</div>

Related

Script does not show original image

Guys I have a script that shows blogger articles, only the images of the articles are of poor quality.
Looking at the script the only part that refers to the image is this
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
css code:
.itemposts img {
float:left;
height:90px;
width:200px;
margin:2px 10px 2px 0px;
-webkit-box-shadow:none;
-moz-box-shadow:none;
box-shadow:none;
background-color:#fafafa;
border:1px solid #dcdcdc;
padding:4px;
}
Does anyone know which part of the code needs to be changed to show the image with the original quality?
added full code full code
<script>
var showPostDate = true,
showComments = true,
idMode = true,
sortByLabel = false,
labelSorter = "Games",
loadingText = "Loading...",
totalPostLabel = "Jumlah posting:",
jumpPageLabel = "Halaman",
commentsLabel = "Komentar",
rmoreText = "Selengkapnya ►",
prevText = "Sebelumnya",
nextText = "Berikutnya",
siteUrl = "https://elfenliedbrazil.blogspot.com/",
postPerPage = 6,
numChars = 370,
imgBlank = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC";
</script>
<script type='text/javascript'>
//<![CDATA[
// -----------------------------------------------------------------------------------------
//
// Original:
// Modified by Taufik Nurrohman
//
// -----------------------------------------------------------------------------------------
var minpage = 6; // Minimum number to display the page
var maxpage = 10; // The maximum number of pages to display
var firstpage = 0; // Detect the first time it is executed
var pagernum = 0; // Contain the page number where we
var postsnum = 0; // Start the first page
var actualpage = 1; // Starting value of the current page (it will change if you click the pagination).
// This is the container template that will be used to insert the posts template, pagination and the posts count
document.write('<div id="toc-outer"><div id="results"></div><div id="itempager" style="position:relative;"><div id="pagination"></div><div id="totalposts"></div><a title="Taufik Nurrohman" style="display:block!important;visibility:visible!important;opacity:1!important;position:absolute;bottom:10px;right:14px;font:normal bold 8px Arial,Sans-Serif!important;color:#666;text-shadow:0 1px 0 rgba(255,255,255,.1);text-decoration:none;" href="http://hompimpaalaihumgambreng.blogspot.com/2012/03/daftar-isi-blogger-dengan-navigasi.html" target="_blank">►TN</a></div></div>');
var _results = document.getElementById('results');
var _pagination = document.getElementById('pagination');
var _totalposts = document.getElementById('totalposts');
// Build the table of contents framework
function showPagePosts(json) {
var entry, posttitle, posturl, postimg, postsumm, replies, monthnames, timepub, output = "";
if (pagernum === 0) {
postsnum = parseInt(json.feed.openSearch$totalResults.$t);
pagernum = parseInt(postsnum / postPerPage) + 1;
}
for (var i = 0; i < postPerPage; i++) {
if ("entry" in json.feed) {
if (i == json.feed.entry.length) break;
entry = json.feed.entry[i];
posttitle = entry.title.$t; // Get the post title
// Get rel="alternate" for truly post url
for (var k = 0, elen = entry.link.length; k < elen; k++) {
if (entry.link[k].rel == "alternate") {
posturl = entry.link[k].href; // This is your real post URL!
break;
}
}
// Get the comments count
for (var l = 0, clen = entry.link.length; l < clen; l++) {
if (entry.link[l].rel == "replies" && entry.link[l].type == "text/html") {
var commentsnum = entry.link[l].title.split(" ")[0]; // This is your comments count
break;
}
}
// If the Blogger-feed is set to SHORT, then the content is in the summary-field
postsumm = ("summary" in entry) ? entry.summary.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : ""; // Get the post summary
// Reduce post summaries to "numChars" characters.
// "numChars" is a variable. You determine the value
if (postsumm.length > numChars) {
postsumm = (numChars > 0 && numChars !== false) ? postsumm.substring(0, numChars) + '...' : "";
}
// Get the post date (e.g: 2012-02-07T12:56:00.000+07:00)
var _postdate = entry.published.$t,
_cdyear = _postdate.substring(0, 4), // Take 4 characters from the "postdate" beginning, it means the year (2012)
_cdmonth = _postdate.substring(5, 7), // Take 2 character 5 step from "postdate" beginning, it mean the month (02)
_cdday = _postdate.substring(8, 10); // Take 2 character 8 step from "postdate" beginning. it means the day (07)
// Month array template
monthnames = (idMode) ? ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"] : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The final product of the post date = (07 Feb 2012) (cdday monthnames cdyear)
timepub = (showPostDate) ? _cdday + ' ' + monthnames[parseInt(_cdmonth, 10) - 1] + ' ' + _cdyear + ' - ' : '';
// The final product of the comments count & comments label (10 Komentar) (commentsnum commentsLabel)
replies = (showComments) ? commentsnum + ' ' + commentsLabel : '';
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
}
}
// Put the whole template above into <div id="results"></div>
_results.innerHTML = output;
_create_pagination();
}
// Build the pagination
function _create_pagination() {
output = "";
var starter = 0;
output += ((actualpage > 1) ? '<a title="' + prevText + '" class="prevjson" href="javascript:_init_script(' + (actualpage - 1) + ')">' + prevText + '</a>' : '<span class="prevjson hidden">' + prevText + '</span>') + '<em style="font:inherit;color:inherit;" class="pagernumber">';
if (pagernum < (maxpage + 1)) {
for (starter = 1; starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
} else if (pagernum > (maxpage - 1)) {
if (actualpage < minpage) {
for (starter = 1; starter < (maxpage - 2); starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else if (pagernum - (minpage - 1) > actualpage && actualpage > (minpage - 1)) {
output += '1';
output += '2';
output += ' ... ';
for (starter = actualpage - 2; starter <= actualpage + 2; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else {
output += '1';
output += '2';
output += ' ... ';
for (starter = pagernum - (minpage + 1); starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
}
}
output += '</em>' + ((actualpage < starter - 1) ? '<a title="' + nextText + '" class="nextjson" href="javascript:_init_script(' + (actualpage + 1) + ')">' + nextText + '</a>' : '<span class="nextjson hidden">' + nextText + '</span>');
_pagination.innerHTML = output;
_totalposts.innerHTML = totalPostLabel + ' ' + postsnum + ' - ' + jumpPageLabel + ' ' + ((actualpage * postPerPage) - (postPerPage - 1)) + ((actualpage < starter - 1) ? ' - ' + (actualpage * postPerPage) : "");
}
// Functions to remove and append the callback script that has been manipulated in the `start-index` parameter
function _init_script(n) {
var parameter = (n * postPerPage) - (postPerPage - 1), old, s,
head = document.getElementsByTagName('head')[0],
url = (sortByLabel) ? siteUrl + '/feeds/posts/summary/-/' + labelSorter + '?start-index=' + parameter : siteUrl + '/feeds/posts/summary?start-index=' + parameter; // Optional: Sort posts by a specific label
if (firstpage == 1) {
// Jump to top
document.documentElement.scrollTop = _results.offsetTop - 30;
document.body.scrollTop = _results.offsetTop - 30;
// Remove the old callback script
old = document.getElementById("TEMPORAL");
old.parentNode.removeChild(old);
}
_results.innerHTML = '<div id="loadingscript">' + loadingText + '</div>';
_pagination.innerHTML = '';
_totalposts.innerHTML = '';
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&max-results=' + postPerPage + '&orderby=published&alt=json-in-script&callback=showPagePosts';
s.id = 'TEMPORAL';
head.appendChild(s);
firstpage = 1;
actualpage = n;
}
// Execute the _init_script() function with parameter as `1` on page load
// So it will show the first page.
window.onload = function() {
_init_script(1);
};
//]]>
</script>
Thumbnails are reduced-size versions of pictures or videos
https://en.wikipedia.org/wiki/Thumbnail
So you need to get the original image
In some cases you have the size in the url, like in this one at the end of url
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs=w720-h110-rw
You can simply remove that part and get the full size of the image
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs
update
In your case you have a url like this
https://1.bp.blogspot.com/xxxxxxx/s72-c/xxxxx.jpg
you can change to
https://1.bp.blogspot.com/xxxxxxx/s640/xxxxx.jpg
This post explain very well how you can use List of all the App Engine images service get_serving_url() URI options

How to print different value for each table row using javascript

I just want to create a multiplication table using Javascript but I don't want each row to have the same result. I will picture that table I want to be created for my work
In this code, the program will print 9 times
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = 1; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
I already make a table for multiplication but I don't want to make all print 10 times. I want to make different for each table cell
I want to make like this picture and I'm new with JavaScript
var times = 1;
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > (9 - times); i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
times++;
}
You can simply add this to the second loop for (i = 1; i <= a; i++) that way you'll achieve what you want.
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 5px">')
for (i = 1; i <= a; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
The simple answer is replace this line for (i=1; i<=9; i++) { with this: for (i=a; i<=9; i++) {
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = a; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
For having the exact same thing as you posted in your picture, this code do the job :
document.write("<table>");
for (a = 9; a > 0; a--) {
document.write("<tr>")
for (i = 9; i > a - 1; i--) {
document.write('<td>' + a + ' x ' + i + ' = ' + a * i + '</td>');
}
document.write('</tr>')
}
document.write("</table>")
Note the use of decrementing loop to match the order of your picture and the usage of the table

change the text of a label and in js and use it from code behind?

I created a list of buttons from code behind, and append them on some div, how ever each button has an onclick java script function
here is how I did it:
string[] messages = CM.GetMessages(Session["USER_EMAIL"].ToString()).Split(new string[] { "$STARTCHAT$" }, StringSplitOptions.None);
string[] usersalone = CM.GetChaters(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
string[] username = CM.GetUserNames(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
for (int i = messages.Length-2; i>=0; i--)
{
Button b = new Button();
b.ID = Session["USER_EMAIL"].ToString()+username[i];
b.Text = "Chat With: " + usersalone[i] ;
b.Width = 250;
b.Height = 100;
b.OnClientClick = "return DisplayMessage('" + messages[i+1] + "','" + username[i] + "','" + Session["USER_EMAIL"].ToString() + "')";
b.Style.Add("background-color", "rgb(246, 246, 246)");
// lblChatwith.Text = username[i];
NewMsgNotArrow.Controls.Add(b);
}
and here is my java script function:
function DisplayMessage(messages, from, username) {
document.getElementById("AllMessages").innerText ="";
document.getElementById("DivDisplayMessage").style.visibility = "visible";
document.getElementById("lblChatwith").innerText = from;
var MessageForEachUser = messages.split("$SAMECHATNEWTEXT$");
for (var i = 0; i < MessageForEachUser.length; i++)
{
var ck = MessageForEachUser[i].indexOf("$" + from.toUpperCase() + "$") > -1;
if (ck == true) {
document.getElementById("AllMessages").innerText += from.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + from.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
if (ck == false) {
document.getElementById("AllMessages").innerText += username.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + username.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
document.getElementById("AllMessages").innerText += MessageForEachUser[i] + "\n______________________________________________________" + "\n";
}
return false;
}
every thing is working well but, when i want to use one of the labels like "lblchatwith" from code behind it return an empty string.

Confetti in Javascript

I'm trying to get my code to randomly place 50 randomly colored circles, or "confetti", within a box. So far all that appears is one black circle in the upper left corner of the box.
"use strict";
window.onload = function() {
document.onclick = create;
};
function trim(data) {
var start;
var whitespace;
var end;
var result;
if (typeof data === "string") {
whitespace = " \n\r\t\f";
start = 0;
} else {
result = data;
}
while ((start < data.length) && (whitespace.indexOf(data.charAt(start)))) {
start = start + 1;
};
end = data.length - 1;
while ((end >= 0) && (whitespace.indexOf(data.charAt(end)))) {
end = end - 1;
};
if (end < start) {
result = "";
} else {
result = data.substring(1 + start, end);
}
return result;
};
function getRandomInteger(upperLimit) {
return Math.floor(Math.random() * (upperLimit + 1));
};
function getRandomRGB() {
var blue;
var green;
var red;
red = getRandomInteger(255);
blue = getRandomInteger(255);
green = getRandomInteger(255);
return "rgb(" + red + "," + green + "," + blue + ")";
};
function createHTMLElement(elementType, id, classInfo, content) {
if (elementType === null) {
elementType = "";
};
trim(elementType);
if (id === null) {
id = "";
}
trim(id);
if (id.length > 0) {
id = " " + "id=" + '"' + id + '"' + " ";
};
if (classInfo === null) {
classInfo = "";
}
trim(classInfo);
if (classInfo.length > 0) {
classInfo = " " + "class=" + '"' + classInfo + '"';
}
if (content === null) {
content = "";
};
trim(content);
return '<' + elementType +
id + classInfo +
'>' + content +
'</' + elementType + '>';
};
function createConfetti(containerId, howMany) {
var element;
var i;
var idPrefix;
var result;
result = "";
idPrefix = "circles";
i = 0;
element = document.getElementById(idPrefix + i);
while (i < howMany) {
result = result + createHTMLElement("span", idPrefix + i, "confetti", "•");
i = i + 1;
} //while
document.getElementById(containerId).innerHTML = result;
while (i < howMany) {
document.getElementById(idPrefix + i).style.color = getRandomRGB();
document.getElementById(idPrefix + i).style.top = getRandomInteger(offsetHeight - 4) + "px";
document.getElementById(idPrefix + i).style.left = getRandomInteger(offsetWidth - 4) + "px";
i = i + 1;
} //while
};
function create() {
createConfetti("container", 50);
};
{
border: 0;
margin: 0;
padding: 0;
}
body {
font-family: "Times New Roman", serif;
font-size: 12pt;
}
#container {
border: 2px solid black;
height: 10em;
line-height: .9em;
margin-left: auto;
margin-right: auto;
position: relative;
width: 30em;
}
.confetti {
font-size: 3em;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Confetti Part 1</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
</head>
<body>
<div id=container></div>
</body>
</html>
You have two issues:
You use the same variable (i) for both loops. But you don't reset i back to zero. Second, you just reference offsetHeight and offsetWidth. I'm assuming you mean the container's width and height? So your updated code should look like:
i=0;
while (i < howMany) {
document.getElementById(idPrefix + i).style.color = getRandomRGB();
document.getElementById(idPrefix + i).style.top = getRandomInteger(document.getElementById(containerId).offsetHeight - 4) + "px";
document.getElementById(idPrefix + i).style.left = getRandomInteger(document.getElementById(containerId).offsetWidth - 4) + "px";
i = i + 1;
} //while
"use strict";
window.onload = function() {
document.onclick = create;
};
function trim(data) {
var start;
var whitespace;
var end;
var result;
if (typeof data === "string") {
whitespace = " \n\r\t\f";
start = 0;
} else {
result = data;
}
while ((start < data.length) && (whitespace.indexOf(data.charAt(start)))) {
start = start + 1;
};
end = data.length - 1;
while ((end >= 0) && (whitespace.indexOf(data.charAt(end)))) {
end = end - 1;
};
if (end < start) {
result = "";
} else {
result = data.substring(1 + start, end);
}
return result;
};
function getRandomInteger(upperLimit) {
return Math.floor(Math.random() * (upperLimit + 1));
};
function getRandomRGB() {
var blue;
var green;
var red;
red = getRandomInteger(255);
blue = getRandomInteger(255);
green = getRandomInteger(255);
return "rgb(" + red + "," + green + "," + blue + ")";
};
function createHTMLElement(elementType, id, classInfo, content) {
if (elementType === null) {
elementType = "";
};
trim(elementType);
if (id === null) {
id = "";
}
trim(id);
if (id.length > 0) {
id = " " + "id=" + '"' + id + '"' + " ";
};
if (classInfo === null) {
classInfo = "";
}
trim(classInfo);
if (classInfo.length > 0) {
classInfo = " " + "class=" + '"' + classInfo + '"';
}
if (content === null) {
content = "";
};
trim(content);
return '<' + elementType +
id + classInfo +
'>' + content +
'</' + elementType + '>';
};
function createConfetti(containerId, howMany) {
var element;
var i;
var idPrefix;
var result;
result = "";
idPrefix = "circles";
i = 0;
element = document.getElementById(idPrefix + i);
while (i < howMany) {
result = result + createHTMLElement("span", idPrefix + i, "confetti", "•");
i = i + 1;
} //while
document.getElementById(containerId).innerHTML = result;
i=0;
while (i < howMany) {
document.getElementById(idPrefix + i).style.color = getRandomRGB();
document.getElementById(idPrefix + i).style.top = getRandomInteger(document.getElementById(containerId).offsetHeight - 4) + "px";
document.getElementById(idPrefix + i).style.left = getRandomInteger(document.getElementById(containerId).offsetWidth - 4) + "px";
i = i + 1;
} //while
};
function create() {
createConfetti("container", 50);
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Confetti Part 1</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script src="ConfettiPart1.js" type="text/javascript"></script>
<style type="text/css">
{
border: 0;
margin: 0;
padding: 0;
}
body {
font-family: "Times New Roman", serif;
font-size: 12pt;
}
#container {
border: 2px solid black;
height: 10em;
line-height: .9em;
margin-left: auto;
margin-right: auto;
position: relative;
width: 30em;
}
.confetti {
font-size: 3em;
position: absolute;
}
</style>
</head>
<body>
<div id=container></div>
</body>
</html>
fouund something
idPrefix = "circles";
i = 0;
element = document.getElementById( idPrefix+i );
while( i < howMany )
{
result=result+createHTMLElement("span", idPrefix+i, "confetti", "•");
i = i+1;
}//while
document.getElementById(containerId).innerHTML=result;
at this point, i = 50, and won´t enter next loop
while( i < howMany )
{

Need some improvement in xml display

i have implemented this code to display xml in html using javascript
current output
Need something like
Here is my code
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
var f = false;
if (n.nodeType !== 3) {
str += '<br><<span class="nn">' + n.nodeName + '</span>>';
if (n.hasChildNodes()) {
f = true;
str += parseXML(n, s++);
}
str += '</<span class="nn">' + n.nodeName + '</span>>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
if (f) {
str += '<br>';
}
}
var str = str.replace(/(<br>)+/g, '<br>');
return str;
}
how i call this
R : xml object
s : initial 0 (i am passing this so that i can display xml as hirarchical view)
Output in second
- is not required
i have post second out as it can be seen while opening xml document in firefox
please ask if any doubt
I solved it myself.
Updated code with the solution
var pre = 0;
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
if (n.nodeType !== 3) {
str += '<br>' + gs(s) + '<b><</b><span class="nn">' + n.nodeName + '</span><b>></b>';
if (n.hasChildNodes()) {
str += parseXML(n, s + 1);
}
if (pre !== 3) {
str += '<br>' + gs(s);
}
str += '<b><</b>/<span class="nn">' + n.nodeName + '</span><b>></b>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
pre = n.nodeType;
}
return str;
}

Categories