Changing a global variable to a window.prompt() variable within a .click function in javascript

I'm currently working on The Odin Project's first project in their curriculum.

For step 4, I am trying to create a window.prompt() that will ask the user for a new number to assign to a pre-existing global variable like so:

var gridSize;
var gridAmount;

    if (gridAmount === "", null, undefined, false || gridAmount < 1 ||gridAmount > 64 || isNaN(gridAmount)){
            var gridSize = 16;
        } else {
            var gridSize = gridAmount;
        };

    function grid() {

        for (var x = 0; x < gridSize; x++) {
            $('#container').append("<div class='grid'></div>");
            $('.grid').height(800 / gridSize);
        };
        for (var x = 0; x < gridSize; x++) {
            $('.grid').append("<div class='row'></div>")
            $('.row').width(800 / gridSize);
            $('.row').height(800 / gridSize);
        };
    };

    $('#reset-squares').click(function(){
        location.reload(true);
        var gridAmount = window.prompt("From 1 to 64, what is your grid's parameters (00 x 00)?");
    });

What I am trying to do is reset the page, then assign the variable gridAmount to a new number defined in the .click() function. Am I missing something? Is this unachievable with the current code structure?

Here's a demo

Thanks in advance!

Answers 1

  • You're right in thinking it may not be possible. The page is reloading before the gridAmount can ever be set.

    You need to pass the value back to the page and set it before you reload the page.

    You could reload the page with a query string ?show_prompt=true (or one that contains a value you need etc.) for example.

    Then you would be able to check if that was set when the page loads / reloads and show the prompt, get the value from the user and set that to var gridAmount at the top of the script.


Related Articles