JQuery not working on divs created by javascript -
this question has answer here:
i working on assignment odin project:
http://www.theodinproject.com/web-development-101/javascript-and-jquery?ref=lc-pb
i cannot jquery .hover work on divs have created.
the project specifies divs should created using javascript or jquery. have done can't jquery work on divs created javascript.
js code below:
function creategrid(resolution) { var wr = document.createelement("div"); wr.setattribute("id", "wrapper"); document.body.appendchild(wr); (x = 0; x<resolution; x++) { (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 desired grid resolution. number must between 3 , 64"); if (resolution > 64 || resolution < 3) { alert("this number beyond acceptable range. pick number between 3 , 64") getres(); } creategrid(resolution); }; //console not showing errors hover not working //after added script below $(document).ready(function(){ $(".pixel").hover(function(){ $(this).css("background-color","black"); }, function(){ $(this).css("background-color", "black"); }); });
you can either modify function add event handler right after creation:
function creategrid(resolution) { var wr = document.createelement("div"); wr.setattribute("id", "wrapper"); document.body.appendchild(wr); (x = 0; x<resolution; x++) { (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 event handler attached each element. or need use delegation , attach event handler static parent element work dynamically created elements using on
,
$(document).on("mouseenter",".pixel",function (e) { }); $(document).on("mouseleave",".pixel",function (e) { });
this way have bind handler mouseenter
, mouseleave
separately though.
Comments
Post a Comment