hackrnaut
hackrnaut

Reputation: 583

Changing Height and Width of Div via Jquery

I'm trying to fill the div container with square boxes. Why doesn't this line work? I can't seem to change the height and width of my div #gridSquare.

$('#gridSquare').css({"height": "38.4", "width": "38.4"});

I'm linking the fiddle with the rest of my code.

Thank you for reading!

Fiddle

What I ultimately want to do is use the squareSide variable to set the hight and width.

Upvotes: 1

Views: 87

Answers (3)

Shrinivas Pai
Shrinivas Pai

Reputation: 7711

Use class instead of an id.

Add this.

$(document).ready(function(){
    var squareSide = 960/25;



    console.log(squareSide);

    for(var rows = 0; rows < 25; rows++){
    $('<div class="gridSquare"></div>').appendTo('.container')
        for(var cols = 0; cols < 25; cols++){
            $('<div class="gridSquare"></div>').appendTo('.container');
            $('.gridSquare').css({"height": "38.4", "width": "38.4"});
        }
    }

    $('.container').on('mouseenter', '.gridSquare', function(){
        $(this).css('background-color', 'white');
    });

});

Fiddle http://jsfiddle.net/5ojjbwms/6/

Upvotes: 1

Matteo Rubini
Matteo Rubini

Reputation: 831

Probably

$('#gridSquare').css({"height": "38.4px", "width": "38.4px"});

Upvotes: 1

Pete
Pete

Reputation: 58462

You need to use a class instead of an id (ids should be unique) and then you want to set the css of the square after you have appended to squares:

var squareSide = 960 / 25;

console.log(squareSide);

for (var rows = 0; rows < 25; rows++) {
  $('<div class="gridSquare"></div>').appendTo('.container')
  for (var cols = 0; cols < 25; cols++) {
    $('<div class="gridSquare"></div>').appendTo('.container')
  }
}

$('.container').on('mouseenter', '.gridSquare', function() {
  $(this).css('background-color', 'white');
});

$('.gridSquare').css({
  "height": "38.4",
  "width": "38.4"
});
.container{
	background-color: grey;
	margin: 0 auto;
	text-align: center;
	font-size: 0;
	margin-bottom: 30px;
	width: 960px;
	height: 960px;
}

.gridSquare{
	background-color: black;
	display: inline-block;
	vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

Also your for loop can be changed to

// 625 = 25 * 25
for (var i = 0; i < 625; i++) {
    $('<div class="gridSquare"></div>').appendTo('.container')
}

Upvotes: 2

Related Questions