Nick Nick - 4 months ago 9
Javascript Question

Can anyone help me make my JavaScript faster?

In my program, I am making divs boxes with JavaScript and it seems to be taking quite a bit of time making a 50X50 grid.It even takes some time to make 20x20 grid. I have looked up how to make my code faster , but none of the suggestions have made an insignificance difference.

This an Odin Project

https://jsfiddle.net/Mulk/yc5rsf1m/#&togetherjs=dVAh1FK7On

$(document).ready(function(){
// Defalut Grid is 16x 16 Grid
CreateBox(16);
CallMeMaybe();

$("#gridbtn").click(function(){
$(".odd").remove();
var numbox =parseInt(prompt("How many boxes would like?"));
CreateBox(numbox);

});

function CreateBox(a) {
var wh = (500/a), i , j ;
for(i=0;i<a;i++){
for(j=0;j<a;j++){
$div = $('<div/>').appendTo('#container').addClass(".odd").attr('class','odd').width(wh).height(wh);

CallMeMaybe();





}}

};

// Play with me


function CallMeMaybe(a){
$(".odd").hover(function(){


var r = Math.floor(Math.random() * (256 - 0) + 0);
var g = Math.floor(Math.random() * (256 - 0) + 0);
var b = Math.floor(Math.random() * (256 - 0) + 0);
var color = "rgb("+r+","+g+","+b+")"
$(this).css("background-color", color);


});
};





// Play with me






});

Answer

This should be faster. It creates an array of the divs and appends them to the DOM all at once. The divs are created with the attributes instead of changing their attributes after they have been added to the DOM. It also attaches the hover handler at the time of creation instead of attaching it after all the boxes have been created. This should significantly reduce the number of DOM manipulations that need to happen.

$(function(){

  function createBox(boxesInRow) {
    var wh = (500/boxesInRow), i , j, divs = [];
    for(i = 0; i < boxesInRow; i++){
        for(j = 0; j < boxesInRow; j++){
            divs.push($('<div/>', {
                "class":'odd',
                height: wh + 'px',
                width: wh + 'px',
                hover: hoverCallback
            }));
        }
    }

    $('#container').empty().append(divs);
  }

  function hoverCallback() {
    var r = Math.floor(Math.random() * 256),
        g = Math.floor(Math.random() * 256),
        b = Math.floor(Math.random() * 256);
    $(this).css("background-color", "rgb("+r+","+g+","+b+")");
  }

  // Default Grid is 16x16 Grid
  createBox(16);

  $("#gridbtn").click(function() {
    var numbox = parseInt(prompt("How many boxes would you like per row?"));
    createBox(numbox); 
  });

});
Comments