Cameron00
Cameron00

Reputation: 11

Need help calling a function

I have a beginner and having trouble having the follow code run. When I hit the reset button the draw() function I defined does not seem to run/produce any output. The previous grid is erased but the new one is not created in its place.

I cannot seem to figure out why. Any help would be greatly appreciated.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Etch-A-Sketch</title>
        <link rel="stylesheet" type="text/css" href="CSS/styles.css"/>
        <script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src = "JS/jquery.js"></script>
        <meta charset="utf-8"/>
    </head>
    <body>
        <h1>Etch-A-Sketch</h1>
        <h3>Cameron Watson</h3>
        <div id='container'></div>
        <div class='divbut'>RESET</div>
    </body>
</html>
#container {    
    border: 1px solid black;
    height: 720px;
    width: 720px;
    margin: auto;
    position: absolute;
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0;
}
.grid {
    height: 45px;
    width: 45px;
    float: left;
}
h1 {
    text-align: center;
}
h3 {
    text-align: center;
}
.divbut {
    border: 1px solid black;
    height: 45px;
    width: 65px;
    text-align: center;
}
$(document).ready(function() {
    draw(16);

    $('.grid').hover(function(){
        $(this).css("background-color", "#00ffff");
    });

    $(".divbut").click(function(){
        $('div').remove('.grid');
        draw(16);
    });
});

function draw(count){
    for (x = 0; x < count; x++) {
        for (y = 0; y < count; y++) {
            $('<div>').addClass('grid').appendTo('#container');
        }
    }
};

Upvotes: 0

Views: 56

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337743

The issue is because you remove the original .grid element which the hover event was bound to. When you create the new .grid elements, the event is no longer bound. To solve this you need to use a delegated event handler:

$('#container').on('mouseenter', '.grid', function(){
    $(this).css("background-color", "#00ffff");
});

Working example

You would have to hook to the mouseeenter event in this case as hover is not a standard event (it's a combined usage of mouseenter and mouseleave).

Also note that, as stated by @hmd, you should call remove directly on the $('.grid') elements:

$(".divbut").click(function() {
    $('.grid').remove();
    draw(16);
});

Upvotes: 1

Related Questions