Reputation: 23
Hello guys i am new to jQuery and I have struggled with no success to solve this problem. I try to generate some divs with the following code and I want to make them clickable so when anyone clicks on them, the background becomes red.
Here is the jquery code which generates the div
function drawCanvas(){
var divHeight = 4;
var counter = 0;
for (var j =0; j <6; j++){
for(var i = 0; i <= 3 ; i++){
var left = j*105;
var top = i *105;
$("#area").append("<div class='tile' style='height:100px; width:100px; position:absolute; top:"+top+"px; left:"+left+"px; border:1px solid black; '></div> ");
}
}
}
$("#canvasSubmit").click(function(){
var radioValue = $("input[name='optionsRadios']:checked").val();
if(radioValue == 1){
$("#area").width(600);
$("#area").height(400);
drawCanvas();
}
else if(radioValue == 2){
$("#area").width(600);
$("#area").height(600);
}
if(radioValue == 3){
$("#area").width(900);
$("#area").height(600);
}
});
and here is what I have tried so far with no success
$(this).find(".tile").click(function(i){
$(this).addClass("red");
});
and here using on()
but it is also not working
$(".tile").on("click", function(){
$(this).addClass("red");
});
Can you please help me???
Upvotes: 2
Views: 101
Reputation: 46
Your code seems to be fine, you just need to have a CSS class for the ".red" class you are adding. Here is a fiddle:
http://jsfiddle.net/madkidflash/bjmpqn4t/
CSS Area:
.red { background-color: red; }
You can also toggle the class if that is more useful.
$(".tile").click(function(i){
$(this).toggleClass("red");
});
Revised Fiddle:
http://jsfiddle.net/madkidflash/bjmpqn4t/2/
Upvotes: 1
Reputation: 7018
You must use event delegation. Your listener should look like:
$('#area').on('click', '.tile', function() {
$(this).addClass('red');
}
Upvotes: 2