Change obj.innerHTML in Javascript? Game of Life - javascript

I have implemented the Game of Life in Javascript. I am thinking about making a combobox which a listof colors to choose from. From there I want to render the obj.innerHTML img source of my grid cells in the game. What would be the best way to go about this?
Here is my code so far for the game:
<br>
<canvas id="canvas" width="100%" height="80%"></canvas>
<button onClick="generateLevel()">Create New Board</button>
<button onClick="step()">Step</button>
<button onClick="multiStep()">Multistep</button>
<script type="text/javascript">
var level;
var lastLevelDrawn;
var lvlWidth = 0;
var lvlHeight = 0;
function step()
{
var tempLevel = new Array(lvlHeight);
for (var y = 0; y < lvlHeight; y++)
{
tempLevel[y] = new Array(lvlWidth);
for (var x = 0; x < lvlWidth; x++)
{
var liveNeighborCount = 0;
var status = level[y][x];
for (var k = y-1; k < y+2; k++)
{
for (var j = x-1; j < x+2; j++)
{
if (k == y && j == x)
{
}
else if (k >= 0 && k < lvlHeight && j >= 0 && j < lvlWidth)
{
if (level[k][j] == "1")
{
liveNeighborCount++;
}
}
}
}
if (level[y][x] == "1")
{
if (liveNeighborCount != 2 && liveNeighborCount != 3)
{
status = "0";
}
}
if (level[y][x] == "0")
{
if (liveNeighborCount == 3)
{
status = "1";
}
}
tempLevel[y][x] = status;
}
}
level = tempLevel;
render();
}
function multiStep()
{
var steps = prompt("How many steps do you want to step?", "10");
for (var x = 0; x < steps; x++)
step();
}
function generateLevel()
{
var width = prompt("How many cells wide?", "10");
var height = prompt("How many cells high?", "10");
lvlWidth = width;
lvlHeight = height;
var output = "";
if (width != null && height != null)
{
level = new Array(lvlHeight);
lastLevelDrawn = new Array(lvlHeight);
for (var y = 0; y < height; y++)
{
level[y] = new Array(lvlWidth);
lastLevelDrawn[y] = new Array(lvlWidth);
for (var x = 0; x < width; x++)
{
level[y][x] = Math.floor((Math.random()*2));
lastLevelDrawn[y][x] = -1;
output += " " + level[y][x];
}
output += "<br>";
}
}
//document.getElementById("demo").innerHTML=output;
setupRender();
}
function changeTile(tile)
{
var x = tile % lvlWidth;
var y = parseInt(tile/lvlWidth);
//document.getElementById("demo").innerHTML=x + ":" + y;
if (level[y][x] == "1")
level[y][x] = "0";
else
level[y][x] = "1";
render();
}
function render()
{
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
for (var y = 0; y < lvlHeight; y++)
{
for (var z = 0; z < lvlWidth; z++)
{
var send = y*lvlWidth + z;
if (lastLevelDrawn[y][z] != level[y][z])
{
lastLevelDrawn[y][z] = level[y][z];
var obj = document.getElementById(send);
if (level[y][z] == "1")
obj.innerHTML = "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
obj.innerHTML = "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
}
}
}
}
function setupRender()
{
var x = "";
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
//x += "<table border='1' col width='((1/lvlWidth)*100)%' col height='((1/lvlHeight)*80)%'>";
for (var y = 0; y < lvlHeight; y++)
{
//x += "<tr>";
for (var z = 0; z < lvlWidth; z++)
{
lastLevelDrawn[y][z] = level[y][z];
//x += level[y][z];
var send = y*lvlWidth + z;
x += "<n id='" + send + "'>";
if (level[y][z] == "1")
x += "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
x += "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
x += "</n>";
}
x += "<br>";
//x += "</tr>";
}
//x += "</table>";
document.getElementById("demo").innerHTML=x;
}
</script>

Related

Is there a better way of finding solution than using nested loops?

I am looking to speed up the process of testing all the combinations based on the nested loops in the piece of code included.
I am currently stuck with JavaScript and NodeJS on Windows 10.
Is there a way to compute this using GPU rather than CPU?
var simulations = 0;
for (let i = 10; i <= 20; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
console.log('testing combination '
+ rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
+ rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
+ rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
);
console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
Implementation of worker threads to the best of my ability.
const {
Worker, isMainThread, parentPort, workerData
} = require('worker_threads');
const os = require('os');
if (isMainThread) {
const startTime = Date.now();
const workers = [];
// const numberOfThreads = 1;
const numberOfThreads = os.cpus().length;
let completed = 0;
let minBreakStep = 10;
let maxBreakStep = 20;
let minMaxElements = [];
for (let i = minBreakStep; i <= maxBreakStep; i++) {
minMaxElements.push(i);
}
const numberOfElements = minMaxElements.length;
const numElementsPerThread = Math.ceil(numberOfElements / numberOfThreads);
let workerIndex = 0;
let allSimulations = 0;
for (let i = minBreakStep; i <= maxBreakStep; i += numElementsPerThread) {
let workerStart = i;
let workerEnd = i + numElementsPerThread - 1;
if (workerEnd > maxBreakStep) {
workerEnd = maxBreakStep
}
const worker = new Worker(__filename, {
workerData: {
workerIndex,
workerStart,
workerEnd,
}
});
worker.on('message', (message) => {
if (message.completed) {
completed++;
console.log('worker ' + message.workerIndex + ' completed ' + message.simulations + ' simulations.');
allSimulations += message.simulations;
}
if (completed === workers.length) {
console.log('Completed all ' + allSimulations + ' done!');
const endTime = Date.now();
const elapsedTime = (endTime - startTime) / 1000;
console.log(elapsedTime + ' second(s) to complete');
}
});
workerIndex++;
workers.push(worker);
}
} else {
let workerIndex = workerData.workerIndex;
let workerStart = workerData.workerStart;
let workerEnd = workerData.workerEnd;
let simulations = 0;
for (let i = workerStart; i <= workerEnd; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
// console.log('testing combination '
// + rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
// + rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
// + rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
// );
// console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
console.log('testing completed');
parentPort.postMessage({
completed: true,
workerIndex: workerIndex,
simulations: simulations,
});
}
Implementation of worker threads to the best of my ability.
const {
Worker, isMainThread, parentPort, workerData
} = require('worker_threads');
const os = require('os');
if (isMainThread) {
const startTime = Date.now();
const workers = [];
// const numberOfThreads = 1;
const numberOfThreads = os.cpus().length;
let completed = 0;
let minBreakStep = 10;
let maxBreakStep = 20;
let minMaxElements = [];
for (let i = minBreakStep; i <= maxBreakStep; i++) {
minMaxElements.push(i);
}
const numberOfElements = minMaxElements.length;
const numElementsPerThread = Math.ceil(numberOfElements / numberOfThreads);
let workerIndex = 0;
let allSimulations = 0;
for (let i = minBreakStep; i <= maxBreakStep; i += numElementsPerThread) {
let workerStart = i;
let workerEnd = i + numElementsPerThread - 1;
if (workerEnd > maxBreakStep) {
workerEnd = maxBreakStep
}
const worker = new Worker(__filename, {
workerData: {
workerIndex,
workerStart,
workerEnd,
}
});
worker.on('message', (message) => {
if (message.completed) {
completed++;
console.log('worker ' + message.workerIndex + ' completed ' + message.simulations + ' simulations.');
allSimulations += message.simulations;
}
if (completed === workers.length) {
console.log('Completed all ' + allSimulations + ' done!');
const endTime = Date.now();
const elapsedTime = (endTime - startTime) / 1000;
console.log(elapsedTime + ' second(s) to complete');
}
});
workerIndex++;
workers.push(worker);
}
} else {
let workerIndex = workerData.workerIndex;
let workerStart = workerData.workerStart;
let workerEnd = workerData.workerEnd;
let simulations = 0;
for (let i = workerStart; i <= workerEnd; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
// console.log('testing combination '
// + rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
// + rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
// + rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
// );
// console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
console.log('testing completed');
parentPort.postMessage({
completed: true,
workerIndex: workerIndex,
simulations: simulations,
});
}
In Node.js, I'm unaware of any easy to use the GPU. Depending on the nature of the work being done to test each combination and the characteristics of your host system, you can use the built-in worker_threads and/or cluster modules to spread out the work. The worker_threads module creates threads within a process. The cluster module creates separate processes.
You can for example use CUDA bindings to perform calculations on GPU. Maybe in this case it would be better to interface a C program and import/export the experimental design and results. https://github.com/kashif/node-cuda / https://www.npmjs.com/package/cuda-node-js
Additionally I would get rid of all these nested loops with something like below. For performance sake maybe get rid of the slicing, and check the parameters as the few lines below are just to get the idea across.
class ExperimentGenerator{
let pointer = 0;
const initialParams = [0,0,0,0,0,0,0,0];
let params = [...initialParams]
const maxValue = [10,10,10,10,10,10,10,10]
nextExperiment = () =>{
if(params[pointer] >= maxValue[pointer]){
pointer++;
//Reset all other parameters
params = [initialParams.slice(0,pointer),params[pointer],initialParams.slice(pointer)];
}
params[pointer]++;
return params;
}
}

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>

JavaScript code working only in Chrome but not in Firefox, IE, Opera and Safari

I'n new to programming and I tried something in JavaScript and it worked well in Chrome. But It fails to work in IE, Firefox, Safari and Opera. Am I doing anything wrong with my code?
function hp(form) {
var count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count10 = 0;
for (var i = 0; i < 3; i++) {
if (form.q1[i].checked == true) {
count1++;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q2[i].checked == true) {
count2++;
}
}
if (count2 !== 1) {
alert("Please Answer 2nd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q3[i].checked == true) {
count3++;
}
}
if (count3 !== 1) {
alert("Please Answer 3rd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q4[i].checked == true) {
count4++;
}
}
if (count4 !== 1) {
alert("Please Answer 4th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q5[i].checked == true) {
count5++;
}
}
if (count5 !== 1) {
alert("Please Answer 5th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q6[i].checked == true) {
count6++;
}
}
if (count6 !== 1) {
alert("Please Answer 6th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q7[i].checked == true) {
count7++;
}
}
if (count7 !== 1) {
alert("Please Answer 7th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q8[i].checked == true) {
count8++;
}
}
if (count8 !== 1) {
alert("Please Answer 8th Question");
return false;
}
for (var i = 0; i < 4; i++) {
if (form.q9[i].checked == true) {
count9++;
}
}
if (count9 !== 1) {
alert("Please Answer 9th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q10[i].checked == true) {
count10++;
}
}
if (count10 !== 1) {
alert("Please Answer 10th Question");
return false;
}
answer1 = (form.q1.value);
answer2 = (form.q2.value);
answer3 = (form.q3.value);
answer4 = (form.q4.value);
answer5 = (form.q5.value);
answer6 = (form.q6.value);
answer7 = (form.q7.value);
answer8 = (form.q8.value);
answer9 = (form.q9.value);
answer10 = (form.q10.value);
var a = parseInt(answer1);
var b = parseInt(answer2);
var c = parseInt(answer3);
var d = parseInt(answer4);
var e = parseInt(answer5);
var f = parseInt(answer6);
var g = parseInt(answer7);
var h = parseInt(answer8);
var ii = parseInt(answer9);
var j = parseInt(answer10);
var c = a + b + c + d + e + f + g + h + ii + j;
//document.getElementById("result").innerHTML= "The selected values are "+"</br>"+a+"</br>"+b+c+d+e+f+g+h+ii+j+"</br>"+c;
if (c <= 20) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 20) && (c <= 25)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 25) && (c <= 30)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 30) && (c <= 40)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 40) && (c <= 50)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 50) && (c <= 60)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 60) && (c <= 65)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 65) && (c <= 75)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 75) && (c <= 90)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
c = 0;
}
I tried this code in local host and i got my desired output in Google Chrome. When i tried the same page in Firefox and other browser, it failed to work. Only checkbox validation is working fine.
Thanks in Advance
From personal experience, I have noticed that Chrome is more forgiving when it comes to small errors. It is strange how you are not getting an error in the debug box at all...
But, a place I can see from reading the code is where you define the variables a,b,c... I recommend placing a comma after each. So, you get:
var a = parseInt(answer1),
b = parseInt(answer2),
c = parseInt(answer3),
d = parseInt(answer4),
e = parseInt(answer5),
f = parseInt(answer6),
g = parseInt(answer7),
h = parseInt(answer8),
ii = parseInt(answer9),
j = parseInt(answer10);
Then here is where I think you have an error. You have var c = ... again after already defining c. So, try removing the var right there.

Javascript - loop through the same array more than once

How do I get the below for loop statement to go through my array more than once?
var clients = new Array("client1", "client2", "client3", "client4", "client5");
var indexCounter;
var holmesminutes = 0;
for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}
Put another loop around the loop.
for (var repeatCounter = 0; repeatCounter < 5; repeatCounter++) {
for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}
}
To stop all the loops when holmesminutes reaches 315:
for (var repeatCounter = 0; repeatCounter < 5 && holmesminutes < 315; repeatCounter++) {
for (indexCounter = 0; indexCounter < clients.length && holmesminutes < 315; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}
}
As you see, you can put any condition you want in the test clause of for, it doesn't have to refer only to the iteration variable.
Maybe try a while loop:
var clients = new Array("client1","client2","client3","client4","client5");
var indexCounter;
var holmesminutes =0;
_i= 0;
while (_i < 2) {
for(indexCounter = 0; indexCounter<clients.length;indexCounter++)
{
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes + "<br>");
_i++;
}
}

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