1

I am writing a JavaScript function for setting the image which is required for my offline browser game. I am stuck on one situation that if by default the user does not passed the gridSize or the value of gridSize becomes null then a default value is set (like 4 by default).How could I get this done.

puzzle.js

setImage: function (images, gridSize) {
    console.log(gridSize);
    console.log(gridSize);
    var percentage = 100 / (gridSize - 1);
    var image = images[Math.floor(Math.random() * images.length)];
    $('#imgTitle').html(image.title);
    $('#actualImage').attr('src', image.src);
    $('#sortable').empty();
    for (var i = 0; i < gridSize * gridSize; i++) {
        var xpos = (percentage * (i % gridSize)) + '%';
        var ypos = (percentage * Math.floor(i / gridSize)) + '%';
        var li = $('<li class="item" data-value="' + (i) + '"></li>').css({
            'background-image': 'url(' + image.src + ')',
            'background-size': (gridSize * 100) + '%',
            'background-position': xpos + ' ' + ypos,
            'width': 400 / gridSize,
            'height': 400 / gridSize
        });
        $('#sortable').append(li);
    }
    $('#sortable').randomize();
}
};
  • Welcome to SO! This is not a bad question in terms of quality, but it has already answered before – Pablo Lozano Sep 05 '17 at 07:36
  • @PabloLozano the link to the answer which you provided is not working for `null` but the answer which is provided by @BaijNR is working for null also.When null value is passed then it is just not showing anything –  Sep 05 '17 at 07:42
  • Check the rest of answers, not only the selected one. The second one explains how to work with "falsy" values. Nevertheless you can (and should, if it solves your problem) select @BaijNR answer as the accepted one – Pablo Lozano Sep 05 '17 at 07:45
  • Yes Thanks that is important and useful and sorry before that I saw only the accepted one!!! –  Sep 05 '17 at 07:47

1 Answers1

0

You can append this line in your function at the start after console.log(gridSize):

 gridSize = gridSize || 4; // If gridSize is null or not passed, default it as 4 or as required.

I have not tried it but think it will work (since you need a default value for the same)...

BaijNR
  • 46
  • 5