Hello i am written some script in jquery and bind that to a click event, but the code do not get activated by click event. But when i put the script in another JavaScript function and bind that JavaScript function to click event listener than the function is able to execute on clicking.
Another thing is that when i bind the script using JavaScript it returns me alert message same number of time as the number of div on which i have clicked i.e. if i click on 3rd div the alert message is shown three times
on my page the dom structure is of pdf.js project and this dom is created dynamically
i want to get the index of grandchild of pagecontainer2 on which user had clicked
following is my script:
<script type="text/javascript">
$(function() {
$(".textLayer > div", "#pageContainer2").click(function () {
var index = $(this).index();
alert("index of div is = " + index);
});
});
</script>
Dom CODE :
<div id="pageContainer2" >
<canvas id="page2" width="741" height="959"></canvas>
<div class="textLayer">
<div>......some text here....</div>
<div>......some text here....</div>
<div>......some text here....</div>
</div>
</div>
<div id="pageContainer3" >
<canvas id="page3" width="741" height="959"></canvas>
<div class="textLayer">
<div>......some text here....</div>
<div>......some text here....</div>
<div>......some text here....</div>
</div>
</div>
If you need to assign a click event handler to a DOM node that is not yet present but will be created later, you need to bind the event handler to an existing node using
onand specify the child nodes:Let’s say that
<div id="pageContainer2">already exists, but you’re creating those divs inside that container on the fly. So the proper sytnax would be:That way, you’re actually binding the event handler to the container, but since most events bubble up the DOM, an event fired by a click on any element inside that container will reach the container itself. Because you specified another selector (`.textlayer > div´), jQuery will then check if the actual element that got clicked on satisfies this selector.
If even #pageContainer2 is created after binding the event handler, you can still bind the event handler to the document itself: