-3

I am working on this assignment from the Odin Project:

http://www.theodinproject.com/web-development-101/javascript-and-jquery?ref=lc-pb

I cannot get jQuery .hover to work on the divs I have created.

The project specifies that divs should be created using javascript or jquery. I have done that but can't get any jquery to work on the divs created by the javascript.

JS code below:

function createGrid(resolution) {
    var wr = document.createElement("div");
    wr.setAttribute("id", "wrapper");
    document.body.appendChild(wr);
    for (x = 0; x<resolution; x++)
        {
        for (i = 0; i<resolution; i++)
        {
            var pix = document.createElement("div");
            pix.setAttribute("class", "pixel"); 
            wr.appendChild(pix);
        };
    var clr = document.createElement("div");
    clr.setAttribute("class", "clearLeft"); 
    wr.appendChild(clr);
    };
};

function getRes(){
    var resolution = prompt("Enter your desired grid resolution.  Number must be between 3 and 64");
if (resolution > 64  || resolution < 3)
    {
        alert("This number is beyond the acceptable range.  Pick a number between 3 and 64")
        getRes();
    }   
createGrid(resolution);
};

//Console is not showing any errors but hover is not working
//after I added the script below
$(document).ready(function(){   
$(".pixel").hover(function(){   
    $(this).css("background-color","black");
    }, function(){
    $(this).css("background-color", "black");
    });
}); 
Will Wilson
  • 335
  • 2
  • 9

1 Answers1

0

You can either modify your function to add the event handler right after creation:

function createGrid(resolution) {
  var wr = document.createElement("div");
  wr.setAttribute("id", "wrapper");
  document.body.appendChild(wr);
  for (x = 0; x<resolution; x++)
    {
      for (i = 0; i<resolution; i++)
      {
        var pix = document.createElement("div");
        pix.setAttribute("class", "pixel"); 
        $(pix).hover(function(){   
           $(this).css("background-color","black");
        }, function(){
           $(this).css("background-color", "black");
        });
        wr.appendChild(pix);
      };
  var clr = document.createElement("div");
  clr.setAttribute("class", "clearLeft"); 
  wr.appendChild(clr);
 };
};

This way you'll end up with an event handler attached to each element. Or you need to use delegation and attach event handler to a static parent element to work with dynamically created elements using on, like

$(document).on("mouseenter",".pixel",function (e) {

});
$(document).on("mouseleave",".pixel",function (e) {

});

This way you have to bind the handler for mouseenter and mouseleave separately though.

T J
  • 42,762
  • 13
  • 83
  • 138