Home > Software engineering >  Why my function to change a grid element to the size of an input of type range doesn't work?
Why my function to change a grid element to the size of an input of type range doesn't work?

Time:04-13

I'm trying to create an Etch-a-Sketch project, I was going well (I think) until start to create a function that apply another size to my grid element, how can I do my function setSize() reads my function showSize() value?

Explanation: My function showSize() shows the value of a range input element, and I need to apply this value to my function populateBoard(), so I have created setSize() function to do that, Am I right creating this intermediary function to do that?

These are my codes:

function populateBoard(size){
    let board = document.querySelector(".board");
    board.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
    board.style.gridTemplateRows = `repeat(${size}, 1fr)`;

    for (let i = 0; i < 256; i  ) {
        let square = document.createElement("div");
        square.style.backgroundColor = "green";
        board.insertAdjacentElement("beforeend", square);
    }
}
populateBoard(16);

function showSize(value) {
    let boardSize = document.querySelector(".show-size").innerHTML = value;
}

function setSize(boardSize) {
    let setSize = document.querySelector(".set");
    setSize.addEventListener("click", () => {
        populateBoard(boardSize);
    });
}
<!DOCTYPE html>
<html>

<head>
    <title>
        Etch-a-Sketch
    </title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="styles.css"> 
    <script src="script.js" defer></script>
</head>

<body>
    <div >
        
        <div >   
        
        </div>

        <div >
            <button >Clear</button>
            <input type="range" min="8" value="16" max="128" step="8" oninput="showSize(this.value)">
            <span >16</span>
            <button >Set</button>
        </div>
    </div>
</body>

</html>

CodePudding user response:

The problem is that you are defining the boardSize variable in the showSize function so that variable is only available in the scope of that function. Please read the following: https://www.w3schools.com/js/js_scope.asp

I suggest you do the following.

document.querySelector(".set").addEventListener("click", () => {
    let boardSize = document.querySelector(".show-size").innerHTML;
    populateBoard(boardSize);
});

function setSize(value) {
    document.querySelector(".show-size").innerHTML = value;
}

Some errors you have is setting the event listener in a function. I would just have a function to set the board size as seen above and then the event listener to populate the board onclick of the set size button.

  • Related