I am creating a hangman game and I have to output images, when the users lives get down from 7-0.
I have put this code into my javascript , however it only outputs the if(lives ==8) image.
Unfortunality it does not seem to work at all ?
I am very new to javascript and when I have read the other answers, I have found them hard to understand.
The fact that it doesn't output , does this mean I have an error in my code somewhere. ?
function setup() {
alphabet = "abcdefghijklmnopqrstuvwxyz";
lives = 8;
var words = ["ayeupmeducks", "pieceofcake", "bullinachinashop", "hangfire","greeneyedmonster", "hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon","afootinthedoor","bitethebullet"];
messages = {
win: 'Congratulations you have won the game of Hangman!',
lose: 'You have been Hanged !!',
guessed: ' already guessed, please try again...',
validLetter: 'Please enter a letter from A-Z'
};
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
hints =
["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
var hintIndex = words
showClue.innerHTML = "Clue: - " + hints [idx];
};
gussedLetter = matchedLetter = '';
numberofMatchedLetters = 0;
/* This chooses the word which will be displayed on the page */
idx = Math.floor(Math.random() * words.length);
currentWord = words[idx];
output = document.getElementById("output");
message = document.getElementById("message");
guessInput = document.getElementById("letter");
message.innerHTML = 'You have ' + lives + ' lives remaining';
output.innerHTML = '';
document.getElementById("letter").value = '';
guessButton = document.getElementById("guess");
guessInput.style.display = 'inline';
guessButton.style.display = 'inline';
letters = document.getElementById("letters");
letters.innerHTML = '<li class="current-word">Current word:</li>';
var letter, i;
for (i = 0; i < currentWord.length; i++) {
/* returns the character at the specified index in a string.*/
letter = '<li class="letter letter' + currentWord.charAt(i).toUpperCase() + '">' + currentWord.charAt(i).toUpperCase() + '</li>';
/* inserts the results node into Dom at the correct place, The BeforeEnd- inside the element, after its last child.*/
letters.insertAdjacentHTML('beforeend', letter);
}
}
function gameOver(win) {
if (win) {
output.innerHTML = messages.win;
output.classList.add('win');
} else {
output.innerHTML = messages.lose;
output.classList.add('error');
}
guessInput.style.display = guessButton.style.display = 'none';
guessInput.value = '';
}
window.onload = setup();
document.getElementById("restart").onclick = setup;
guessInput.onclick = function () {
this.value = '';
};
document.getElementById('hangman').onsubmit = function (e) {
if (e.preventDefault) e.preventDefault();
output.innerHTML = '';
output.classList.remove('error', 'warning');
guess = guessInput.value;
if (guess) {
if (alphabet.indexOf(guess) > -1) {
if ((matchedLetter && matchedLetter.indexOf(guess) > -1) || (gussedLetter && gussedLetter.indexOf(guess) > -1)) {
output.innerHTML = '"' + guess.toUpperCase() + '"' + messages.guessed;
output.classList.add("warning");
}
else if (currentWord.indexOf(guess) > -1) {
var lettersToShow;
lettersToShow = document.querySelectorAll(".letter" + guess.toUpperCase());
for (var i = 0; i < lettersToShow.length; i++) {
lettersToShow[i].classList.add("correct");
}
for (var j = 0; j < currentWord.length; j++) {
if (currentWord.charAt(j) === guess) {
numberofMatchedLetters += 1;
}
}
matchedLetter += guess;
if (numberofMatchedLetters === currentWord.length) {
gameOver(true);
}
}
else {
gussedLetter += guess;
lives--;
message.innerHTML = 'You have ' + lives + ' lives remaining';
if (lives === 0) gameOver();
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
return false;
};
var x = document.createElement("IMG");
if (lives==8){
x.setAttribute("src", "Hangman-0.png");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
x.setAttribute("alt", "Hangman");
document.body.appendChild(x);}
if (lives==7){
x.setAttribute("src", "Hangman-1.png");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
x.setAttribute("alt", "Hangman");
document.body.appendChild(x);}
From looking at you code, you can simplify a lot - each image has the same height, width, and alt, so you can move all of that out of the function. Also, assuming the src attribute is just a number that is incrementing, you can instead do something like:
var num_lives = 8;
var lives_left = 8;
function guess() {
lives_left--;
x.setAttribute('src', 'Hangman-' + (num_lives - lives_left) + '.png');
}
So, as a working example, your code would basically be:
var url = 'https://www.oligalma.com/downloads/images/hangman/files/';
const num_lives = 10;
var lives = 10;
var x = document.createElement("IMG");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
x.setAttribute("alt", "Hangman");
x.setAttribute("src", url + (num_lives - lives) + '.jpg');
document.body.appendChild(x);
function change() {
lives--;
if (lives < 0) {
lives = num_lives;
}
x.setAttribute("src", url + (num_lives - lives) + '.jpg');
}
<button onClick="change()">Guess</button>
Related
New to coding, can someone tell me whats wrong, I'm trying to create a Guess-a-word game, it was working before but changed a couple for loops and isn't working
var guessLetters
var currentWord
var guesses
var wrongGuesses
var correctGuesses
var currentWord
var badLetters
var index
var guessWords = ["baseball","basketball","football","soccer","volleyball","golf","frisbee","cricket","bowling","billards","polo","pool","swimming","gymnastics","badminton","handball","lacrosse","surfing","tennis","softball","rugby","ice skating","ice hockey","track and field","squash","table tennis", "archery","judo","water polo","field hockey","four square","rowing","snowboarding","skiing","climbing","running","wrestling","horse racing","fencing","curling","diving"]
function startGame(){
currentWord = guessWords[Math.floor(Math.random()*guessWords.length)];
document.getElementById("Random Test").innerHTML = currentWord;
document.getElementById("demo").innerHTML = "The blanks represent letters in the hidden word are here: " + secretBlanks(currentWord);
guessLetters = []
badLetters = []
index = []
guesses = 0
}
function answer() {
var currentGuess = document.getElementById("currentGuess").value;
document.getElementById("guessLetter").innerHTML= currentGuess;
for (i = 0; i < guessLetters.length; i++) {
if (currentGuess === guessLetters[i]){
document.getElementById("Guess Repeat").innerHTML ="You already guessed that silly!";
return}
}
document.getElementById("Guess Repeat").innerHTML = "Valid Guess";
guessLetters.push(currentGuess);
document.getElementById("Already guessed").innerHTML = guessLetters;
var match=0;
for (j = 0; j < currentWord.length; j++){
if (currentGuess=currentWord[j]){
index.push(j);
match++;
}
}
if (match=0){
badLetters.push(currentGuess)
document.getElementById("Guess Result").innerHTML = "Incorrect Guess";
document.getElementById("Incorrectguess").innerHTML = "These are your incorrect guesses" + badLetters;
} else{
document.getElementById("Guess Result").innerHTML = "Correct Guess";
document.getElementById("demo").innerHTML = "The blanks represent letters in the hidden word are here: " + secretBlanks(currentWord);
}
}
function secretBlanks(secretWord) {
correctLettersOUT = "";
for (var i = 0; i < secretWord.length; i++) {
if(index.includes(i)){
correctLettersOUT+=(secretWord[i])
correctLettersOUT+=(" ")
}else{
correctLettersOUT+=("_ ");
}
} return correctLettersOUT;
}
You forgot a lot of semi-colons. Here take this version:
var guessLetters;
var currentWord;
var guesses;
var wrongGuesses;
var correctGuesses;
var currentWord ;
var badLetters;
var index;
var guessWords = ["baseball","basketball","football","soccer","volleyball","golf","frisbee","cricket","bowling","billards","polo","pool","swimming","gymnastics","badminton","handball","lacrosse","surfing","tennis","softball","rugby","ice skating","ice hockey","track and field","squash","table tennis", "archery","judo","water polo","field hockey","four square","rowing","snowboarding","skiing","climbing","running","wrestling","horse racing","fencing","curling","diving"];
function startGame(){
currentWord = guessWords[Math.floor(Math.random()*guessWords.length)];
document.getElementById("Random Test").innerHTML = currentWord;
document.getElementById("demo").innerHTML = "The blanks represent letters in the hidden word are here: " + secretBlanks(currentWord);
guessLetters = [];
badLetters = [];
index = [];
guesses = 0;
}
function answer() {
var currentGuess = document.getElementById("currentGuess").value;
document.getElementById("guessLetter").innerHTML= currentGuess;
for (i = 0; i < guessLetters.length; i++) {
if (currentGuess === guessLetters[i]){
document.getElementById("Guess Repeat").innerHTML ="You already guessed that silly!";
return;
}
}
document.getElementById("Guess Repeat").innerHTML = "Valid Guess";
guessLetters.push(currentGuess);
document.getElementById("Already guessed").innerHTML = guessLetters;
var match=0;
for (j = 0; j < currentWord.length; j++){
if (currentGuess=currentWord[j]){
index.push(j);
match++;
}
}
if (match=0){
badLetters.push(currentGuess);
document.getElementById("Guess Result").innerHTML = "Incorrect Guess";
document.getElementById("Incorrectguess").innerHTML = "These are your incorrect guesses" + badLetters;
} else{
document.getElementById("Guess Result").innerHTML = "Correct Guess";
document.getElementById("demo").innerHTML = "The blanks represent letters in the hidden word are here: " + secretBlanks(currentWord);
}
}
function secretBlanks(secretWord) {
correctLettersOUT = "";
for (var i = 0; i < secretWord.length; i++) {
if(index.includes(i)){
correctLettersOUT+=(secretWord[i]);
correctLettersOUT+=(" ");
}else{
correctLettersOUT+=("_ ");
}
} return correctLettersOUT;
}
I am trying to render child elements of an element if the element is in view or removing the content if not in view like below on scroll event like below
list.addEventListener('scroll', function () {
var elements = document.querySelectorAll('.aBox');
var toBe = counter - 1 - elements.length;
for (var i = 0; i < elements.length; i++) {
var inView = visibleY(elements[i]),
ele = elements[i].querySelector('.item');
if (inView === false && ele) {
console.log("Not in visible, keeping it none");
var height = elements[i].clientHeight;
elements[i].style.height = height + "px";
elements[i].innerHTML = "";
} else if(!ele){
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
elements[i].innerHTML = str;
}
}
});
It seems working but if I have a look at the DOM this is not working as expected. Someone please help me to find the problem, fiddle.
Update
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
if (typeof minArray === "object") {
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
}
cb();
}, function () {
callback()
});
}
Fiddle
Hi I have solved this problem. Posting here, so that it will be more helpful for people who want to work on mobiles to display very large lists with virtual scrolling
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = "Hello Dudes..." + i;
}
Array.prototype.chunk = function (chunkSize) {
var array = this;
return [].concat.apply([],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
}));
}
arr = arr.chunk(50);
var list = document.getElementById('longList');
var button = document.getElementById('loadMore');
var counter = arr.length,
aBoxLen = 1;
function appendBox() {
var div = document.createElement('div'),
str = "";
div.className = "aBox";
var minArray = arr[counter - aBoxLen];
for (var i = 0; i < minArray.length; i++) {
str += "<div class='item'>" + minArray[i] + "</div>";
}
div.innerHTML = str;
div.setAttribute('index', counter - aBoxLen);
var box = document.querySelector('.aBox');
if (box) {
list.insertBefore(div, box);
} else {
list.appendChild(div);
}
aBoxLen += 1;
}
appendBox();
button.addEventListener('click', function () {
appendBox();
});
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
console.log(element.getAttribute('index'));
var minArray = arr[element.getAttribute('index')],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
cb();
}, function () {
// callback()
});
}
var delay = false;
var timeout = null;
list.addEventListener('touchmove', function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
updateData();
}
}, delay);
});
None of the solutions were specifically designed for mobiles, so I have implemented this.
I think there is lots of space for improvement in this. If anybody want to improve it, please feel free to make it
Demo
var a = document.querySelectorAll('.post .content div');
var b = a[7].childNodes;
for(i=0;i<b.length;i++){
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if(b[i].nodeType === 3){
var ahref = document.createElement('a');
ahref.className="easyBBurlFetch";
ahref.href=b[i].nodeValue.replace(exp,'$1');
ahref.innerText=b[i].nodeValue.replace(exp,'$1');
b[i].parentNode.insertBefore(ahref,b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
Someone gave me the answer as I had this code though it wasn't working correct. Though I have the issue now if my text is like so:
This is just a test so click here www.youtube.com which then becomes
www.youtube.com%20which%20then%20becomes
It doesn't event keep the first line of text, I just need to parse the url while keeping the surrounding text.
In need the output to save the actual surrounding text but parse the urls that are inside the text to html anchor tags <a> so that they can then be clickable and actually follow through to a real website and not have unnessarcy text inside it from what my user was writing about. Thank you
UPDATE
I've got closer to making this work-- But I'm having a problem with the first text in the string is saying Undefined I've been debugging this and can't seem to figure out why this is happening. Here is code
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== "" && validURL(textArray[j])) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML+= textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
newHTML = "";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
Testing Code
Just need to figure out the undefined and why it's adding it
this regexp will do the job
exp = /href="(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])"/ig;
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
if (validURL(b[i].textContent)) {
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== undefined && textArray[j] !== "" && validURL(textArray[j]) && textArray[j] !== null) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML += textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
div.className = "easyDiv";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
newHTML = "";
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
By taking the textNodes and splitting them into an array I can then change the url into an html element. Then taking the array elements seeing if there is outerHTML or not then placing it in a new string and replacing that textNode now with a workable link.
Working example
Good evening,
So, I have been working on a project, where I have to upload an image form the pc to a canvas and when the image is there I have to add elements over the image that are available over the canvas.
What i got so far is the dragable elements to canvas (example), and here is the code code:
<script type="text/javascript">
contador = 0;
function start(e) {
e.dataTransfer.effecAllowed = 'copyMove';
e.dataTransfer.setData("Data", e.target.id);
e.dataTransfer.setDragImage(e.target, 10, 10);
e.target.style.opacity = '0.4';
}
function end(e){
e.target.style.opacity = '';
e.dataTransfer.clearData("Data");
}
function enter(e) {
e.target.style.border = '3px dotted #555';
}
function leave(e) {
e.target.style.border = '';
}
function over(e) {
var elemArrastrable = e.dataTransfer.getData("Data");
var id = e.target.id;
if (id == 'cuadro1'){
return false;
}
if (id == 'cuadro2'){
return false;
}
if (id == 'papelera')
return false;
}
function drop(e){
var elementoArrastrado = e.dataTransfer.getData("Data");
e.target.appendChild(document.getElementById(elementoArrastrado));
e.target.style.border = '';
tamContX = $('#'+e.target.id).width();
tamContY = $('#'+e.target.id).height();
tamElemX = $('#'+elementoArrastrado).width();
tamElemY = $('#'+elementoArrastrado).height();
posXCont = $('#'+e.target.id).position().left;
posYCont = $('#'+e.target.id).position().top;
x = e.layerX;
y = e.layerY;
if (posXCont + tamContX <= x + tamElemX){
x = posXCont + tamContX - tamElemX;
}
if (posYCont + tamContY <= y + tamElemY){
y = posYCont + tamContY - tamElemY;
}
document.getElementById(elementoArrastrado).style.position = "absolute";
document.getElementById(elementoArrastrado).style.left = x + "px";
document.getElementById(elementoArrastrado).style.top = y + "px";
}
function eliminar(e){
var elementoArrastrado = document.getElementById(e.dataTransfer.getData("Data"));
elementoArrastrado.parentNode.removeChild(elementoArrastrado);
e.target.style.border = '';
}
function clonar(e){
var elementoArrastrado = document.getElementById(e.dataTransfer.getData("Data"));
elementoArrastrado.style.opacity = '';
var elementoClonado = elementoArrastrado.cloneNode(true);
elementoClonado.id = "ElemClonado" + contador;
contador += 1;
elementoClonado.style.position = "static";
e.target.appendChild(elementoClonado);
e.target.style.border = '';
}
</script>
Now, i have seen great examples here for uploading images to canvas (http://jsfiddle.net/influenztial/qy7h5/), but how can i combine the image upload into canvas and then the scripting of adding elements to this same image?
Any help is greatly appreciated.
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:
"Message: '1' is null or not an object"
The line of code where this is present is 225 which is:
var B = b[1].toLowerCase();
I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:
<script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================
/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}
function filterNum(str) {
re = /\$|,|#|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
table = document.getElementById("dg");
if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/
tags = document.getElementById("dg").getElementsByTagName("SPAN");
txt = "";
var newText = "a";
for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
if(i%2!=0){
var newValue = filterNum(tags[i].innerHTML);
}else var newName =tags[i].innerHTML;
if((i>2) & (i%2!=0)){
newText = newText+newValue+subdelimit+newName+delimit;
if(typeof newText != 'undefined'){
txt = newText;
txt = txt.substr(9);
/* alert(txt);*/
}
}
}
}/*else alert ('Hidden');*/
function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}
function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});
var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
Any help or explanations is much appreciated
Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere? Firefox and IE may be responding differently to the problem of an undefined array.