0

I have a grid of divs that I want to change when I hover over them. I'm trying to make it so the background color changes to white, and back to grey when the mouse is no longer hovering over them. I've been searching for a while, and I can't seem to find an answer that addresses what I'm looking for.

var d = ("<div class='square'></div>");
var value = [];


function createGrid(numSquares) {
    var area = $('#g_area');
    var squareSize = Math.floor(area.innerWidth() /numSquares);
    var n =0;
    for (var i = 0, len = (numSquares*numSquares); i < len; i++) {
        area.append(d);
        for (var j = 0; j < numSquares; j++) {
            $(d).attr('id', n);
            n++;
            value[n] = 0;
        }
    }


    $('.square').height(squareSize);
    $('.square').width(squareSize);
};

function resetGrid() {
    $(".square").remove();
}

$(document).ready(function () {
    createGrid(32);

});

$('.square').hover(function() {
    $(this).css({backgroundColor: '#FFFFFF'}) ;
    $(this).css({backgroundColor: '#C8C8C8'}) ;
});

jsfiddle: https://jsfiddle.net/psyonix/1g9p59bx/16/

3 Answers 3

5

Your syntax for hover was incorrect, you need to pass two functions:

$('.square').hover(function () {
    $(this).css({
        backgroundColor: '#FFFFFF'
    });}, function(){
    $(this).css({
        backgroundColor: '#C8C8C8'
    });
});

jsFiddle example

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That works, but only in jsfiddle. For some reason when I update the scripts locally nothing happens. Any clue as to why that may be? The code is exactly as it appears in the example.
Naw, I just needed to wrap it properly.
1

You need to define the handlerOut. This should work. https://jsfiddle.net/1g9p59bx/18/

$('.square').hover(function () {
    $(this).css({
        backgroundColor: '#FFFFFF'
    });
}, function() {
    $(this).css({
        backgroundColor: '#C8C8C8'
    });
});

6 Comments

Thanks! That works, but only in jsfiddle. For some reason when I update the scripts locally nothing happens. Any clue as to why that may be? The code is exactly as it appears in the example.
Try clearing your local browser cache on the page. Ctrl + F5 usually works. Have a look at this: superuser.com/questions/36106/…
Just tried that, no luck. So odd that it works just fine in jsfiddle.
Any errors in your console? F12 opens the console, check if there are any javascript errors.
jsFiddle wraps your code in a window onload call by default.
|
0

Why not just put this on your css?

.square:hover
{
    background-color: #FFFFFF;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.