1

I am not an expert in javaScrit , but i have the following concern. I have the following Script :-

<script type="text/javascript">
        $(document).ready(function () {
            $("#DCSort").click(function () {

what this indicates is the following :- 1. the script will run when the document finishes loading. 2. when the DCSort DOM element is clicked .

my question is as follow:- let say that after the document loaded , a new element with DCsort have replaced the old DCSort element , will the original javaScrip fire when the newly added DCSort element has been added using an Ajax call and i use click on it ? Thanks

john Gu
  • 7,691
  • 60
  • 207
  • 407

2 Answers2

2

Replace this -

$("#DCSort").click(function () {

with this -

$("body")on('click', '#DCSort', function () {

This uses event delegation to account for items added to the DOM after it is originally rendered.

Jay Blanchard
  • 33,530
  • 16
  • 73
  • 113
  • what what is the difference between $("body") & $(document) ?? – john Gu May 08 '14 at 10:22
  • 1
    Document is more encompassing than body. Body here is selector for the body tag which should be all you have to use for 99.99% of event delegation. When doing delegation I usually recommend that you delegate only as high as you need to in the bubble chain. – Jay Blanchard May 08 '14 at 12:26
  • Hi, it worked great for me, but can you please explain what is the difference? – FarrisFahad Jun 05 '15 at 10:44
  • @FarrisFahad many people use `document` as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally [you should delegate to the nearest parent that exists at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Jun 05 '15 at 11:30
1

You need event delegation in that case:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','#DCSort',function () {
Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120