I have this code:
$(".div").click(function ()
{
alert("hi");
});
...but when I create new div
:
$("body").append("<div>1</div>");
...and click on this div
, it doesn't say "hi".
I know that I can do onclick="callfunction()"
on the div
element, but I would like to avoid using that method.
Problems
You were attempting to create a bind on an element that didn't yet exist - so it couldn't be bound.
You used .div
as a selector. The selector .div
is looking for an element with class="div"
rather than an element of type div
.
Solution 1 - Delegation
With delegation you create a bind on an element that exists in the structure above where you will be dynamically adding an element that you want to listen for.
To use delegation, change to this:
$("body").on("click", "div", function ()
{
alert("hi");
});
Here is an example showing delegation vs binding on a future element without delegation:
Fiddle
Solution 2 - Bind to element on creation
The alternative would be to add the bind on the creation of the new element, that would look something like this:
$newEle = $("<div>1</div>").click( function() {
alert("hi");
});
$("body").append($newEle);