changing 'x' variable needs to update 2 functions but only updates one

I am very new to programming and I don't know the where to look to sort this problem. My brain just isn't seeing the problem as to why it won't work.

I am trying to update the 'x' variable on button click to affect both the 'gridGen' for loop function as well as the 'boxSize' css function. gridGen doesn't change and i still end up with the default of 16*16 (256) boxes, but they are sized the way they need to be.

edit: say I enter '4' in the prompt, i'll get 4 columns of boxes in my container div, but the horizontal rows will continue down the page to still total 256

$(document).ready(function() {
  var x = 16;
    $('#button').mouseup(function() {
      this.blur()
    });
    $('#gridContainer').hover(function fill() {
      $('.gridBox').mouseenter(function() {
        $(this).addClass('fill');
      });
    });
    var gridGen = function() {
      for (var i = 0; i < x * x; i++) {
      var $gridBox = $('<div class="gridBox"></div>');
      $('#gridContainer').append($gridBox);
      }
    };
    var boxSize = function() {
      var size = 640 / x;
      $('.gridBox').css('width', size).css('height', size);
    };
    $('#button').click(function() {
      $('.gridBox').removeClass('fill');
      //i need this to update x in 'gridGen' function
      //only seems to update in 'boxSize' function
      x = prompt('Enter Dimensions', 'square of...');
      boxSize();
      gridGen();
    });
    boxSize();
    gridGen();
});

JsFiddle

Answers 1

  • You need to empty the container before adding boxes

    var gridGen = function() {
      $('#gridContainer').empty()
        for (var i = 0; i < (x * x); i++) {
          var gridBox = $('<div class="gridBox"></div>');
          $('#gridContainer').append(gridBox);
        }
    };
    

    Native function prompt() returns a string, you need to parse that string into the Number

    p = prompt('Enter Dimensions', 'square of...');
    
    n = parseInt(p, 10)
    if (!isNaN(n)) {
      x = n
    }
    

    Woking version https://jsfiddle.net/gyr5djhy/1/


Related Articles