I am trying to achieve code reusability by whenever a div is clicked, it gives out the div's numberDiv attribute. It works on the first default div that has a class divClassSelector, but I have some other js code that whenever you press the button "+1 Div", inserts another div. Then, when I try to alert the newly created div's numberDiv attribute, it does not work. I am assuming that it is because the newly created div did not exist in the DOM when the page was first loaded, therefore it cannot find the new div. I could be wrong though.
Does anybody know a workaround to this issue? Any help is much appreciated.
Here's my code:
//HTML
...
<body>
<div class="divClassSelector" numberDiv="1"></div>
<button id="plusOneDiv">+1 Div</button>
</body>
...
//My JS:
//Code to alert the div's numberDiv attribute value
$(".divClassSelector").on("click", function(){
var numberDiv = $(this).attr("numberDiv");
alert(numberDiv);
});
//Code to insert another div
var count = 2;
$("#plusOneDiv").click(function(){
$(body).append(<div class="divClassSelector" numberDiv="'+count+'">');
count++;
});
Thank you for your help in advance and cheers!
UPDATE 1:
Does anyone know how to instead on clicking the div, trigger an event that is triggered by having the "focus" on a form input field, that is, when you click on it and are interacting with it. I tried by using the "focus" method, but it kept alerting the same thing over and over, until I closed the tab, then I could escape from the alert infinite loop. Thanks!
data-div-no="count"for div attribute its html standard$(body).delegate('.className', 'click', function() {//your code goes here});or follow this link api.jquery.com/delegate$(body).append(<div class="divClassSelector" numberDiv="'+count+'">');you are missing'<divalert()inside afocus()handler. Your focus handler fires, which pops up the alert, which fires theblur()event. You close the alert, which fires thefocus()event, which pops up the alert, and you have an infinite loop. If you simply avoid using analert(), binding events tofocus()will work fine.