I am having trouble getting the new .on click to work using 1.7.
For dynamically created links, such as the ones generated by clicking the Create button, those links need the same click function as the static links in the DOM.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
function createDivs(){
content = '<div class="tile-button"><a class="tile-action" href="#" rel="1234" alt="Open">Dynamic Link</a></div>';
$(content).appendTo("#dynamicArea");
$('.tile-action').bind('click',function(){});
}
$(document).ready(function(){
$('#createButton').on("click", createDivs);
$('#destroyButton').on("click", function(event){
$("#dynamicArea").html("");
});
$('.tile-action').on("click", function(event){
var linkalt = $(this).attr("alt");
var linkrel = $(this).attr("rel");
alert(linkalt + " " + linkrel);
return false;
});
});
</script>
</head>
<body>
<button id="createButton">CREATE</button> <button id="destroyButton">Destroy :(</button>
<div id="dynamicArea"></div>
<br>
<a class="tile-action" href="#" rel="1234" alt="Open">Link</a><!-- works -->
</body>
</html>
In this simplified example of my problem, when you click the Create button a dynamic link appears. When you click that nothing happens and those dynamic links do not call the alert like the static link does.
onmethod takes second argument as the selector on which the event should be triggered which you are missing. Also the root element should be the container which will contain the dynamic elements. In your case it is#dynamicArea. Try this.You should understand the working of
on. We are selecting#dynamicAreaelement and usingonmethod on it passing the selector.tile-action. jQuery will attach a click event on#dynamicAreaand whenever any element is clicked inside#dynamicAreathe event will be bubbled to#dynamicArea. At this point it will try to see if the selector which we have passed as second parameter toonmatches or not. If it matches then it triggers the event otherwise it will not do anything just bubble up the event if we don’t stop it.