Changing colour of each array element

- 1 answer

Ad

I am new to HTML/CSS/JavaScript/Jquery/ I have an array of div tags which are represented as boxes. I would like to change the colour of the boxes when I hover over them but I am not sure how to access each div tag and change its properties.

HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="stylesheet3.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="script3.js"></script>
    <body>
        <div class="wrapper">
        </div>
    </body>
</head>
</html>

CSS:

    body 
{
    background:#000;
}
.square 
{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    border:2px solid #73AD21;
    height: 2.5rem;
    width: 2.5rem;
    background-color: white;
}

Javascript/Jquery:

       $(document).ready(function() {
       for(i=0; i<16; i++) {
       $('.wrapper').append('<div class="line">');
           for(j=0; j<16; j++) {
               $('.wrapper').append('<div class="square">'+j+'</div>');
           }
       $('.wrapper').append('</div>');
   }
   /*$('.wrapper').hover(function()) {
    $(this).css("background","#F00");
   }*/
   });

When I add the commented lines in Javascript/Jquery section, the whole webpage becomes black.

Ad

Answer

Ad

When I add the commented lines in JavaScript/jQuery section, the whole webpage becomes black.

That's because there is a syntax error. When this occurs, none of the .square elements are being appended, which is exactly why you are seeing a blank page.

The .hover() method expects two functions as parameters (a hover-in, and hover-out callback). Therefore it seems like you want the following:

Example Here

$('.wrapper .square').hover(function() {
  $(this).css("background", "#f00");
}, function() {
  $(this).css("background", "#fff")
});

However, you can do this with pure CSS using the :hover pseudo-class. You don't actually need jQuery for this.

Example Here

.square:hover {
  background-color: #f00;
}
Ad
source: stackoverflow.com
Ad