Saturday, 14 September 2013

select the last added element using JQuery

select the last added element using JQuery

So I have a simple bit of code. Nothing serious, or life-threatening. I'm
just trying to use JavaScript to fill out an empty html file with some
basic 100x100 elements by clicking on the last element created. Problem
is: I can't actually get my code to register the last element created,
only the last initial element. What could I be doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Container Rainbow</title>
<style type="text/css">
div{ width:100px;height:100px; }
#head{ background-color:rgba(100,0,100,.8);}
#wrapper{width:100%;height:auto;}
div#wrapper > div{float:left;}
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var lastDiv;
var rgba = new Array();
rgba[0] = 110; rgba[1] = 0; rgba[2] = 110; rgba[3] = 1;
$(document).ready(function(){
lastDiv = $("div").last();
lastDiv.on("click", function(){
rgba[0] += 5;
rgba[2] += 5;
var newDiv = $("<div></div>")
.addClass("hatchling")
.css("background-color",
"rgba("+rgba[0]+",0,"+rgba[2]+",1)")
$(this).after(newDiv);
lastDiv=newDiv;
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="head"></div>
</div>
</body>
</html>

No comments:

Post a Comment