简体   繁体   中英

Changing colour of a div using jQuery

I'm trying to change the colour of a singular div using jQuery. I'm 80% sure my code should work but I'm not sure why it's not working. I've tried to use loads of different methods such as mouseenter, hover, addClass, toggleClass etc. But for the life of me I can't figure out what's going on. Help please?

JAVASCRIPT

$(document).ready(function(){
blackMode();
genDivs(10);

});

/* Black mode - changes colours of cells to black */
function blackMode() {
$('.cell').hover(
    function (){
        $(this).css({"background-color":"black"});   
    },
    function (){
        $(this).css({"background-color":"white"});
    });
}

/* creates the divs in a 10x10 grid */

function genDivs(v) {
    var e = document.getElementById('container'); //This is what we want to append the rows
    for (var i = 0; i < v; i++) {
        var row = document.createElement("div"); // This creates each row that is selected.
        row.className="row"; // This declares the class name for the created div.
        for(var j = 0; j < v; j++) {
            var cell = document.createElement("div");
            cell.className="cell";
            row.appendChild(cell);
        }
        e.appendChild(row);
    }
}

HTML

<html>
<head>
    <script type="text/javascript" src="jquery-1.11.3.min.js"></script>
    <script src="Script.js"></script>
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway" />
    <link rel="stylesheet" type="text/css" href="Stylesheet.css"></link>
</head>
<body>
    <h1 class="title">Etch-a-Sketch</h1>
    <div id="container">

    </div>
</body>

UPDATE:

Sorry, I haven't notice you are in fact using .cell class on element you're inserting dynamically - but still give them some height and more important -> first insert elements and then use jQuery to bind events:

$(document).ready(function(){
    genDivs(10);
    blackMode();
});

another fiddle

The version you had before didn't work because by the time you called blackMode function that applied hover handlers none elements with class .cell were in DOM.

ORIGINAL ANSWER:

You are applying hover functions on elements that have cell class, but you haven't used that in your HTML. Also when your div has no contents it'll have 0px height and effect won't be visible.

Add .cell class to you div:

<div class="cell">
</div>

And give it some height via CSS (or add sth inside):

.cell {
    height: 400px;
}

jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM