I am trying to convert this old javascript into jquery in order to learn jquery.
The goal of the old javascript was to add a box to the page when the button "add box" is clicked. when the box itself is clicked on, display a unique id.
I am stuck on how to correctly code the div, and add a box onto it.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>E10W12</title>
<meta charset="UTF-8">
<style>
.clrBox {
background-color: orange;
width: 50px;
height: 50px;
margin: 10px;
}
</style>
<script src="jquery-2.0.3.js"></script>
<script src="E10W12.js"></script>
</head>
<body>
<form>
<input type="button" id="addButton" value="Add Box">
</form>
</body>
</html>
Old Javascript:
window.onload = init;
var i= 0;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick(e) {
i++;
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.setAttribute("id","Box"+i);
div.onclick=function(){handleBoxClick(div);}
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
function handleBoxClick(el){
alert(el.id);
}
New JQuery to replace Javascript:
var i = 0;
$(function() {
$( '#addButton').click(function(){
i++;
Not sure what to do here?
});
});
Alright, I got it using the two answers provided below. Thanks guys!
Solution:
$(function() {
var i = 0;
$( '#addButton').click(function(){
i++;
$('<div/>', {
'id': 'Box' + i,
'class': 'clrBox'
}).appendTo('body');
$("div").click(function () {
alert(this.id);
})
});
});