I'm making a gem-puzzle. I have a save button that after clicking on page reload shows the last saved state of the game. But when I reload the page, the table is rendered but the move click event doesn't work. How can this be fixed? What new arguments need to be passed to the function moveThisTile? Or should I save something else in localstorage? To explain my code: the startNewGame function is called to create the fifteen puzzle. showTable cycles through the two-dimensional array arrayForBoard and generates the necessary HTML for the fifteen puzzle board. moveThisTile takes two arguments that tell the program which tile of the fifteen puzzle needs to be moved
let moves = 0;
let table;
let rows;
let columns;
let textMoves;
let arrayForBoard;
let volumeOn = true;
function start() {
let button = document.getElementById('newGame');
button.addEventListener('click', startNewGame, false );
textMoves = document.getElementById('moves');
table = document.getElementById('table');
rows = 4;
columns = 4;
startNewGame();
}
function startNewGame() {
let arrayOfNumbers = new Array();
let arrayHasNumberBeenUsed;
let randomNumber = 0;
let count = 0;
moves = 0;
rows = document.getElementById('rows').value;
columns = document.getElementById('columns').value;
textMoves.innerHTML = moves;
arrayForBoard = new Array(rows);
for (let i = 0; i < rows; i++){
arrayForBoard[i] = new Array(columns);
}
arrayHasNumberBeenUsed = new Array( rows * columns );
for (let i = 0; i < rows * columns; i++){
arrayHasNumberBeenUsed[i] = 0;
}
for (let i = 0; i < rows * columns; i++){
randomNumber = Math.floor(Math.random()*rows * columns);
if (arrayHasNumberBeenUsed[randomNumber] == 0) {
arrayHasNumberBeenUsed[randomNumber] = 1;
arrayOfNumbers.push(randomNumber);
}else {
i--;
}
}
count = 0;
for (let i = 0; i < rows; i++){
for (let j = 0; j < columns; j++){
arrayForBoard[i][j] = arrayOfNumbers[count];
count++;
}
}
showTable();
}
let tbody = document.createElement('tbody');
document.querySelector('#table').appendChild(tbody);
function showTable() {
for (let tr of document.querySelectorAll("#table tr")) {
tr.remove();
}
for (let i = 0; i < rows; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++) {
let cell = document.createElement('td');
if (arrayForBoard[i][j] == 0) {
cell.className = 'blank';
} else {
cell.className = 'tile';
cell.draggable = true;
cell.addEventListener('click', () => {
moveThisTile(i, j);
if(volumeOn) {
sound()
}
})
cell.innerHTML =arrayForBoard[i][j];
}
tr.appendChild(cell);
}
tbody.appendChild(tr);
}
};
function moveThisTile(tableRow, tableColumn) {
if (checkIfMoveable(tableRow, tableColumn, 'up') ||
checkIfMoveable(tableRow, tableColumn, 'down') ||
checkIfMoveable(tableRow, tableColumn, 'left') ||
checkIfMoveable(tableRow, tableColumn, 'right') ) {
incrementMoves();
} else {
alert('ERROR: Cannot move tile!\nTile must be next to a blank space.');
}
if (checkIfWinner()) {
stopTimer();
alert(`Congratulations! You solved the puzzle in ${moves} moves and in ${document.querySelector('#timespan').innerText}.`);
startNewGame();
}
}
function checkIfMoveable(rowCoordinate, columnCoordinate, direction) {
let rowOffset = 0;
let columnOffset = 0;
if (direction == 'up') {
rowOffset = -1;
} else if (direction == 'down') {
rowOffset = 1;
} else if (direction == 'left') {
columnOffset = -1;
} else if (direction == 'right') {
columnOffset = 1;
}
if (rowCoordinate + rowOffset >= 0 && columnCoordinate + columnOffset >= 0 &&
rowCoordinate + rowOffset < rows && columnCoordinate + columnOffset < columns
) {
if ( arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] == 0) {
arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] = arrayForBoard[rowCoordinate][columnCoordinate];
arrayForBoard[rowCoordinate][columnCoordinate] = 0;
showTable();
return true;
}
}
return false;
}
document.querySelector('.save-btn').addEventListener('click', () => {
localStorage.setItem('currentGame', document.querySelector('tbody').innerHTML);
localStorage.setItem('currentMoves', document.querySelector('#moves').innerHTML);
localStorage.setItem('currentTime', document.querySelector('#timespan').innerHTML);
})
window.addEventListener('load', () => {
if(localStorage.getItem('currentGame') !== null) {
tbody.innerHTML = localStorage.getItem('currentGame');
document.querySelector('#moves').innerHTML = localStorage.getItem('currentMoves');
document.querySelector('#timespan').innerHTML = localStorage.getItem('currentTime');
} else {
start();
}
}, false );
Related
So I have a checkers game, and I am trying to get it so that you can jump over multiple spaces. It works if you jump the max amount of spaces, but if you don't, say you can jump over two spaces, and you choose to jump over only one, it still removes both pieces even though you only jumped over one of the pieces. I think the problem has is inside the checkForJump() function, and it seems like every time the function is called, it returns the same array, any help would be appreciated.
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
Here is some of the other code, relating to that could also be the source of the problem
function jumpTile(tileID) {
this.tilesToRemove = [];
this.tileID = tileID;
};
let numBlackPieces = 12;
let numWhitePieces = 12;
let adjacentTileValues = [7, 9, -7, -9];
let availableSpaces = [
[],
[],
[],
[]
];
function checkValidSpace(buttonPressed, piece) {
// if button is adjacent to selectedbutton
if (buttonPressed == selectedButton + 7 || buttonPressed == selectedButton + 9 || buttonPressed == selectedButton - 9 || buttonPressed == selectedButton - 7) {
return true;
} else {
let valid = false;
// checks if there is a valid jump
checkForJump(selectedButton,[],true);
// foreach of the possible tiles, if the button pressed is one of them than remove all pieces in that tiles remove list
for (let i = 0; i < availableSpaces.length; i++) {
for (let j = 0; j < availableSpaces[i].length; j++) {
if (buttonPressed == availableSpaces[i][j].tileID) {
valid = true;
console.log("availableSpaces[" + i + j + "] is " + availableSpaces[i][j].tileID + "");
remove(availableSpaces[i][j].tilesToRemove);
return true;
}
}
}
if (valid == false)
return false;
}
}
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
function isSpaceAlreadyInArray(spot, arrayIndex) {
let SpaceAlreadyInArray = false;
for (let j = 0; j < availableSpaces[arrayIndex].length; j++) {
if (availableSpaces[arrayIndex][j].tileID == spot) {
SpaceAlreadyInArray = true;
}
}
return SpaceAlreadyInArray;
}
function clearAvailableMoves() {
for (let i = 0; i < availableSpaces.length; i++) {
availableSpaces[i].pop();
}
}
function remove(removeList, button) {
for (let i = 0; i < removeList.length; i++) {
board.value[removeList[i]] = empty;
board.buttons[removeList[i]].textContent = empty;
if (piece == black) {
numBlackPieces--;
checkForWin(numBlackPieces);
} else if (piece == white) {
numWhitePieces--;
checkForWin(numWhitePieces);
}
}
clearAvailableMoves();
};
I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.
function BoxSplash()
{
this.sample = [];
var test = false;
this.col = color(129)
this.changeColour = function()
{
this.col = color(random(0,255),random(0,128),random(0,255))
}
this.intersect = function(other)
{
for(var i = 0; i < numberss; i++)
{ var currentBox = this.sample[i]
var d = dist(currentBox.x,currentBox.y,other.x,other.y)
if(d < currentBox.width + other.width)
{
return true;
}
else
{
return false
}
}
noLoop()
}
this.draw = function()
{
stroke(255)
line(0,windowHeight/2,windowWidth,windowHeight/2)
stroke(0)
for(var i = 0; i < numberss; i++)
{
var box = {
x:random(0,windowWidth - 50),
y:random(windowHeight/2 ,windowHeight - 50),
width:50,
height:50,
speedX:random(1,5),
speedY:random(1,5)
}
this.sample.push(box)
}
//use numberss variable to work with gui
for(var i = 0; i < numberss; i++)
{
fill(this.col)
rect(this.sample[i].x,this.sample[i].y,50,50)
}
this.move()
}
this.move = function()
{
for(var i = 0; i < numberss; i++)
{
var shape = this.sample[i]
shape.x += shape.speedX
shape.y += shape.speedY
if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
{
shape.speedX = -shape.speedX
}
if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
{
shape.speedY = -shape.speedY;
}
for(var j = 0; j < numberss; j++)
{
var others = this.sample[j]
var d = dist(shape.x,shape.y,others.x,others.y)
if( i != j && d < shape.width + others.width)
{
test = true;
}
else
{
test = false
}
if(test)
{
this.col = color(255,0,0)
}
}
}
}
}
You should visit this link and transform their circles into your boxes.
1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d
2nd:
if (d < object1.h + object2.h) {
// Enter your code here
}
I'm programming a checkers game for a high school project. I have a weird variable behaviour and I can't figure out why it's happening. Let me show you the code:
var player = 1;
var lastClicked;
var wasClicked = false;
var isEmpty = new Array(8);
for (var i = 0; i < 8; i++) {
isEmpty[i] = new Array(8);
for (var j = 0; j < 8; j++) {
isEmpty[i][j] = true;
}
}
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { CheckIandJForLater(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function CheckIandJForLater(i, j) { // A function which is meant to show the weird behavior, which prevents me from using function I want to use in the event listener
alert("Function i: " + i);
alert("Function j: " + j);
}
function DeployPieces() {
CreateBoard();
var pieceIndex = 1;
for (var i = 0; i < 8; i++) {
if (i < 3) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td1 = document.getElementById("td" + i + j);
var circle1 = document.createElement("span");
circle1.setAttribute("class", "redCircle");
circle1.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle1.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td1.appendChild(circle1);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td2 = document.getElementById("td" + i + j);
var circle2 = document.createElement("span");
circle2.setAttribute("class", "redCircle");
circle2.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle2.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td2.appendChild(circle2);
isEmpty[i][j] = false;
}
}
}
else if (i > 4) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td3 = document.getElementById("td" + i + j);
var circle3 = document.createElement("span");
circle3.setAttribute("class", "whiteCircle");
circle3.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle3.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td3.appendChild(circle3);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td4 = document.getElementById("td" + i + j);
var circle4 = document.createElement("span");
circle4.setAttribute("class", "whiteCircle");
circle4.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle4.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td4.appendChild(circle4);
isEmpty[i][j] = false;
}
}
}
}
}
function AlertToPressOnSquare() {
alert("Player " + player + ", please press on the square to which you would like to move the piece");
if (player == 1)
player = 2;
else if (player == 2)
player = 1;
}
function MoveToSquare(i, j) { //The function I want to use in the td1 event listener
if (wasClicked && isEmpty[i][j]) {
var lastClickedId = lastClicked.getAttribute("id");
var lastClickedLocation = lastClickedId[6] + lastClickedId[7];
var v1 = parseInt(lastClickedId[6], 10);
var v2 = parseInt(lastClickedId[7], 10);
var tdFrom = document.getElementById("td" + lastClickedLocation);
var tdTo = document.getElementById("td" + i.toString() + j.toString());
if (lastClicked.getAttribute("class") == "whiteCircle") {
if (v1 == i - 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
else if (lastClicked.getAttribute("class") == "redCircle") {
if (v1 == i + 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
alert("Player " + player + ", please press on the piece you would like to move");
wasClicked = false;
}
}
So, the weird behavior is as follows: Every time I click on a td in the table and run the CheckIandJForLater function, I get the value 8 for both i and j. They should not get these values, as i and j are supposed to be updated in the for loop. Moreover, they should never reach the value of 8, since both the loops run between 0 and 7.
It's also worth noting that if I put alert(i); and alert(j); regularly, without the CheckIAndJForLater function, their values are printed fine.
I really struglle in finding out how to solve this weird behavior. May someone help me? Thank you.
Why is that behavior happening? Is there a solution?
I'm trying to code a game and I want to make it so that when you click a button, it increases the number. My game is like a mining game and you click to get ores and at the top right is a box which tells you what you are mining and you can see what you are mining, except when I click the mine button, it comes with the error which says ReferenceError: hello is not defined. The function hello is the function which gives you the ores.
I have tried fixing up some other functions which give you helpers in exchange for help but it didn't change anything, also I checked on stack overflow, but there wasn't anything that could help me. (Keep in mind I am 10 years old)
HTML:
<div class="mwrapper">
<button id="minebutton" onclick="hello()">Mine!</button>
</div>
JavaScript:
//defining the vars.
var stonei = 0;
var deepness = 0;
var stone = 0;
var silveri = 0;
var silver = 0;
var goldi = 0;
var gold = 0;
var platinumi = 0;
var platinum = 0;
var diamondi = 0;
var diamond = 0;
var alexandritei = 0;
var alexandrite = 0;
var amethysti = 0;
var amethyst = 0;
var unobtaniumi = 0;
var unobtanium = 0;
var emeraldi = 0;
var emerald = 0;
var tubi = 0;
var tub = 0;
var blockN;
var block = 0;
var money = 0;
var stoneSold = 0;
var silverSold = 0;
var goldSold = 0;
var clickers = 0;
var moneyEver = 0;
var BpS = 0;
//defining element to shorten code later
var blockEl = document.getElementById("block");
var btxtEL = document.getElementById("btxt");
var moneyEl = document.getElementById("money");
//changing what the 'Block you are mining' says
var findBlock = function(b) {
if (b === 0) {
blockEl.style.backgroundColor = "grey";
btxt.innerHTML = "Stone";
blockN = "stone";
}
else if (b === 1) {
blockEl.style.backgroundColor = "silver";
btxt.innerHTML = "Silver";
blockN = "silver";
}
else if (b === 2) {
blockEl.style.backgroundColor = "gold";
btxt.innerHTML = "Gold";
blockN = "gold";
}
else if (b === 3) {
blockEl.style.backgroundColor = "rgb(90, 89, 89)";
btxt.innerHTML = "Platinum"
blockN = "platinum";
}
else if (b === 4) {
blockEl.style.backgroundColor = "rgb(185, 242, 255)";
btxt.innerHTML = "Diamond"
blockN = "diamond";
}
else if (b <= 10) {
btxt.innerHTML = "Not coded yet";
}
//hehe
else {
btxt.innerHTML = "WHAAAA?????????";
}
}
//adds materials to the left sidebar
var createBlock = function(b) {
if (b === 0) {
stonei += 1;
stone += 1;
document.getElementById("stonei").innerHTML = stonei;
document.getElementById("stone").innerHTML = stone;
}
else if (b === 1) {
silveri += 1;
silver += 1;
document.getElementById("silveri").innerHTML = silveri;
document.getElementById("silver").innerHTML = silver;
}
else if (b === 2) {
goldi += 1;
gold += 1;
document.getElementById("goldi").innerHTML = goldi;
document.getElementById("gold").innerHTML = gold;
}
else if (b === 3) {
platinumi += 1;
platinum += 1;
document.getElementById("platinumi").innerHTML = platinumi;
document.getElementById("platinum").innerHTML = platinum;
}
else if (b === 4) {
diamondi += 1;
diamond += 1;
document.getElementById("diamondi").innerHTML = diamondi;
document.getElementById("diamond").innerHTML = diamond;
}
//not coded rest
}
//From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//for finding the block when you mine
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//when you click the mine button it does this
var hello = function() {
if (deepness === stone + silver + gold + platinum + diamond && stone >= stonei && silver >= silveri && gold >= goldi && platinum >= platinumi && diamond >= diamondi && stoneSold == stone - stonei && moneyEver == money + clickers &&typeof hsjsahjkd === 'undefined' || hsjsahjkd === null) {
if (deepness <= 50) {
block = 0;
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 50, deepness < 150) {
block = getRandomInt(0, 2);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 150, deepness < 250) {
block = getRandomInt(0, 3);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 250, deepness < 350) {
block = getRandomInt(0, 4);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 350) {
block = getRandomInt(0, 5);
findBlock(block);
deepness += 1;
createBlock(block)
}
}
else {
btxt.innerHTML = "Cheater.";
stonei = 0;
deepness = 0;
stone = 0;
silveri = 0;
silver = 0;
goldi = 0;
gold = 0;
platinumi = 0;
platinum = 0;
diamondi = 0;
diamond = 0;
alexandritei = 0;
alexandrite = 0;
amethysti = 0;
amethyst = 0;
unobtaniumi = 0;
unobtanium = 0;
emeraldi = 0;
emerald = 0;
tubi = 0;
tub = 0;
stoneSold = 0;
silverSold = 0;
goldSold = 0;
clickers = 0;
moneyEver = 0;
BpS = 0;
console.log("You cheated. The game restarted.")
if (typeof hsjsahjkd == 'undefined') {
var hsjsahjkd = 1;
}
else {
hsjsahjkd += 1;
}
document.getElementById("cheat").innerHTML = hsjsahjkd;
}
}
Sorry, but the functions needed are quite long. If you want to see the whole code, go to megagames.me/games/mining.html
I expected the out put of hello() to increment some of the ores, but it gave ReferenceError: hello is not defined.
Make sure your JavaScript is linked in the head tag or above the button. Otherwise you'll be calling a function that doesn't exist yet. An easy way to remember is to think of it as a book, you read from top to bottom the same way JavaScript executes top to bottom.
Also, try using Let and Const instead of Var and try using Switch Cases instead of if else all over. :-)
There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>