Have a question

So I’m testing something out with document.getElementById("c5)'s innerhtml. When you click the no square and place it on any other empty square, I want the original place of the no square to disappear. I was able to kind of do it, but it seems that when you click that empty spot where no used to be the code allows the square to be clickable. My goal is to not have it be clickable because the innerhtml is empty and I’m not what’s causing it.

It might be a scoping issue, but I have no idea how to fix it.

Codepen: https://codepen.io/bbg4/pen/NWzBwYo

Hey @yhean890 ,

If you add a .removeEventListener("click", myFunction); ?

function createTaskElement(submittedVal, sub, submittedRow) {
  // ...

  const vals = document.getElementById(tr.id).parentElement;
  vals.replaceChild(tr, vals.childNodes[submittedRow]);

  // Remove the click event listener from the original square
  removeClickEventListener(document.getElementById(sub));
  
  // ...
}

hmm. I’m a bit confused on how to add it in or what it does
.

Basically, I’m trying to ensure that when you click on a new square, the old square’s value disappears, the new square updates with a new value, and old square classifies as a square with no innerhtml that can trigger this code here:

else if(blackSquare[i].innerHTML === ""){
        blackSquare[i].addEventListener("click", e =>{
            if(arr.length > 0){
                sense.push(blackSquare[i]);
                counter++;
                add()
                updateLocalStorage() 
            } 
        })
      }

Perhaps an option would be to add an click event listener for all squares. Inside the handle function, evaluate whether it has innerHTML with event.target.innerHTML and handle it.

Interesting… I’ve never heard of event target before. How does it work? Also, I’m not sure what “handle” means.

Inside the addEventListener method you can access the elemte that was clicked.

squares.addEventListener("click", (e) => {
    const square = e.target
    //do something with square
});

To extract the element clicked content in JavaScript, you can use the event.target property. This property refers to the DOM element that triggered the event. Once you have the target element, you can access its content through various properties, such as innerHTML, textContent, or value, depending on the type of element and the content you want to extract.

Once you have this element, you can manipulate various aspects of the element such as text content, attributes, style, or even its structure depending on your requirements. Just be sure to use the appropriate methods and properties to make the changes you want. That’s what I meant by “handle”.

JavaScript Events (w3schools.com)
Introduction to browser events (javascript.info)

gotcha and to add an eventlistener to all squares… Can I attach an event listener to document.getElementBy(“squares”) so I can target all the squares?

Pretty much I’m making a checkers game and I’m trying to get piece movement down btw

javascript - Adding click event listener to elements with the same class - Stack Overflow

Oh, sweet. I’ll take a look at this. So let’s say that i made it where i added an event listenere to all the squares, set it to where if arr is greater than 0, the clicked square innerhtml will disappear, and clicked the document.getElementById(“c5”) square. I know the innerhtml will disappear, but since the line: document.getElementById(“c5”).innerhtml = “no” is a global value, will it mean that that square is still clickable since the BlackSquare[i] function didn’t reflect the updated innerhtml change?

I took a better look. Your code was really cool. This project has been a challenge for me.
I believe you are right regarding the global scope of element selection with innerHTML=“no”.
We need to find a way to control the state of the element, you did a good job with localStorage. Maybe it’s a solution to update the actual element with innerHTML = “no” in the global scope using localStorage.

I made some changes. What do you think?

//localStorage.clear();
let count = 0;
let arr = [];
const blackSquares = [];
let pen = JSON.parse(localStorage.getItem("pen")) || [];

let sense = [];
let counter = 0;

//table side
const w = 8;
const h = 8;

const initialementId = "c5";

const moves = [];

function createGrid() {
  let numbers = ["a", "b", "c", "d", "e", "f", "g", "h"];
  let table = document.getElementById("myTable");
  for (let i = 0; i < w; i++) {
    let row = document.createElement("tr");
    table.appendChild(row);
    row.id = "set" + i;

    for (let e = 0; e < h; e++) {
      let square = document.createElement("td");
      square.className = "squares";
      square.id = numbers[i] + e;
      row.appendChild(square);
    }
  }
}
createGrid();

const squaresArray1 = [
  document.getElementById("set0"),
  document.getElementById("set2"),
  document.getElementById("set4"),
  document.getElementById("set6")
];
const squaresArray2 = [
  document.getElementById("set1"),
  document.getElementById("set3"),
  document.getElementById("set5"),
  document.getElementById("set7")
];

const rate = squaresArray2.length

function squares() {

  for (let i = 0; i < rate; i++) {
    const set1 = [
      squaresArray1[i].children[1],
      squaresArray1[i].children[3],
      squaresArray1[i].children[5],
      squaresArray1[i].children[7]
    ];
    const set2 = [
      squaresArray2[i].children[0],
      squaresArray2[i].children[2],
      squaresArray2[i].children[4],
      squaresArray2[i].children[6]
    ];
    blackSquares.push(...set1, ...set2);
  }
}

squares();

function updateLocalStorage() {
  localStorage.setItem("pen", JSON.stringify(pen));
}

function add() {
  const obj = {
    value: arr[count - 1],
    ids: sense[counter - 1].id,
    row: sense[counter - 1].cellIndex
  };
  pen.push(obj);
  createTaskElement(obj.value, obj.ids, obj.row);
}

function createTaskElement(submittedVal, sub, submittedRow) {
  const tr = document.createElement("td");
  tr.textContent = submittedVal;
  tr.className = "squares";
  tr.id = sub;

  const vals = document.getElementById(tr.id).parentElement;
  vals.replaceChild(tr, vals.childNodes[submittedRow]);
  document.getElementById("c5").innerText = "";
  console.log(vals);

  arr = [];
  sense = [];
  counter = 0;
  count = 0;

  document.getElementById(tr.id).addEventListener("click", (e) => {
    count++;

    arr.push(document.getElementById(tr.id).textContent);
  });
}

function display() {
  for (let i = 0; i < pen.length; i++) {
    createTaskElement(pen[i].value, pen[i].ids, pen[i].row);
  }
}

const initiaElement = document.getElementById(`${initialementId}`);

function buttonSquares(element) {

    if (!element) {
        return 
    }

    const squareList = document.querySelectorAll('.squares');
    element.innerText = "no";

    squareList.forEach(square => {
        if (square.textContent !== "") {
            square.addEventListener("click", (event) => {
                count++;
                arr.push(square.id);
                console.log(arr)
                console.log("yes");
                return event.target
            });
        } else {
          square.addEventListener("click", (event) => {

            if (arr.length > 0) {
              sense.push(square);
              counter++;
              add();
              updateLocalStorage();
            }
            element.innerText = "";
            event.target.innerText = "no";
            arr.push(event.target.id);
            moves.push(event.target.id);
            console.log("Move ok!!!!")
            return event.target
          });
        }
    })
}

const actualElementId = buttonSquares(initiaElement);
const newMove = document.getElementById(`${actualElementId}`)
buttonSquares(newMove)
display();

I have add EventListener to all squares, added some variables, but still needs a lot of changes.

It looks pretty cool so far. Since I’m trying to emulate a checkers board, I’m trying to only get the black squares to be able to move values to and from. It’s alright if you can’t figure it out, I think I have an idea. Pretty much my goal is that if you click on one of the black squares, the last black square value will turn to nothing, the innerhtml is transfered to the new square, anf the old black square becomes a new clickable empty square to transfer values to and from. Like i said, i think this all hinges on the fact that the document values are declared globally.

I’m just trying to figure out how to change global variables tbh

It looks pretty cool so far. Since I’m trying to emulate a checkers board, I’m trying to only get the black squares to be clickable and have moveable values. I may have an idea though. What if I redo my code and somehow precreate squares that already have values in them… I may be on to something here, but I wonder if i can create dynamic appendable html elements that I can put on the squares and have the values inside of them, and when you click on an old square, my code can recreate the html element value with the innerhtml value already there, add/append it to a new square that I click, and unappend the old html element in the old square. All of this being in local storage, of course.

Hey @yhean890,

I´ve got something, the “no” is moving. I created a moves array and each move I add the target element id to the the end of the array and call recursively buttonSquares() with the the last item of moves. so it update the “no” to this new element.

I comment some functions related to localstorage just to test.

Try it out :

localStorage.clear();
let count = 0;
let arr = [];
const blackSquares = [];
let pen = JSON.parse(localStorage.getItem("pen")) || [];

let sense = [];
let counter = 0;

//table side
const w = 8;
const h = 8;

const moves = [];

const initialementId = "c5";

function createGrid() {
  let numbers = ["a", "b", "c", "d", "e", "f", "g", "h"];
  let table = document.getElementById("myTable");
  for (let i = 0; i < w; i++) {
    let row = document.createElement("tr");
    table.appendChild(row);
    row.id = "set" + i;

    for (let e = 0; e < h; e++) {
      let square = document.createElement("td");
      square.className = "squares";
      square.id = numbers[i] + e;
      row.appendChild(square);
    }
  }
}
createGrid();

const squaresArray1 = [
  document.getElementById("set0"),
  document.getElementById("set2"),
  document.getElementById("set4"),
  document.getElementById("set6")
];
const squaresArray2 = [
  document.getElementById("set1"),
  document.getElementById("set3"),
  document.getElementById("set5"),
  document.getElementById("set7")
];

const rate = squaresArray2.length

function squares() {

  for (let i = 0; i < rate; i++) {
    const set1 = [
      squaresArray1[i].children[1],
      squaresArray1[i].children[3],
      squaresArray1[i].children[5],
      squaresArray1[i].children[7]
    ];
    const set2 = [
      squaresArray2[i].children[0],
      squaresArray2[i].children[2],
      squaresArray2[i].children[4],
      squaresArray2[i].children[6]
    ];
    blackSquares.push(...set1, ...set2);
  }
}

squares();

//function updateLocalStorage() {
//  localStorage.setItem("pen", JSON.stringify(pen));
//}
//
//function add() {
//  const obj = {
//    value: arr[count - 1],
//    ids: sense[counter - 1].id,
//    row: sense[counter - 1].cellIndex
//  };
//  pen.push(obj);
//  createTaskElement(obj.value, obj.ids, obj.row);
//}

//function createTaskElement(submittedVal, sub, submittedRow) {
//  const tr = document.createElement("td");
//  tr.textContent = submittedVal;
//  tr.className = "squares";
//  tr.id = sub;
//
//  const vals = document.getElementById(tr.id).parentElement;
//  vals.replaceChild(tr, vals.childNodes[submittedRow]);
//  document.getElementById("c5").innerText = "";
//  console.log(vals);
//
//  arr = [];
//  sense = [];
//  counter = 0;
//  count = 0;
//
//  document.getElementById(tr.id).addEventListener("click", (e) => {
//    count++;
//
//    arr.push(document.getElementById(tr.id).textContent);
//  });
//}

//function display() {
//  for (let i = 0; i < pen.length; i++) {
//    createTaskElement(pen[i].value, pen[i].ids, pen[i].row);
//  }
//}

const initiaElement = document.getElementById(`${initialementId}`);

function buttonSquares(element) {

    if (!element) {
        return 
    }

    element.innerText = "no";

    blackSquares.forEach(square => {

        console.log(square)
        if (square.id !== element.id) {
            square.innerText = ""
        }
        square.addEventListener("click", (event) => {
            if (square.textContent !== "") {
                count++;
                arr.push(square.id);
                console.log(arr)
                console.log("yes");
                return event.target
            } else {
                arr.push(event.target.id);
                moves.push(event.target.id);
                console.log("Move ok!!!!")
                sense.push(square);
                counter++;
                //add();
                //updateLocalStorage();
                const newElement = document.getElementById(`${moves[moves.length - 1]}`);
                buttonSquares(newElement)
            }
        })
    })
}

buttonSquares(initiaElement);

Try it out

I´ve changes the css just to adjust the size of the square to fit the “no”

.squares {
    padding: 20px;
    border: 1px solid;
    display: inline-grid;
    min-height: 1.5rem;
    min-width: 1.5rem;
  }
  
  tr {
    display: inline-grid;
  }
  
  #a1,
  #a3,
  #a5,
  #a7 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #b0,
  #b2,
  #b4,
  #b6 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  
  #c1,
  #c3,
  #c5,
  #c7 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #d0,
  #d2,
  #d4,
  #d6 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #e1,
  #e3,
  #e5,
  #e7 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #f0,
  #f2,
  #f4,
  #f6 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #g1,
  #g3,
  #g5,
  #g7 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  #h0,
  #h2,
  #h4,
  #h6 {
    background-color: rgba(0, 0, 0, 0.788);
  }
  

To achieve what you are looking for, you can follow these steps in JavaScript:

Add a click event to each square.
When you click on a square, check if the square is empty.
If the square is empty, do not allow it to be clicked.
If the square is not empty, move its contents to the destination square and empty the original square.

Thanks! I plugged the code and it looked like it worked. I didnt look at what the code was so i didnt cheat. Im going to try to figure it out by myself but im glad to know that its possible to do.

That last part is the hard part because in order to get started with that process there has to be a square that already has a value in it. It’s difficult because to have a value in a square, it must be set up globally which means I can’t permanently empty the original square.