0

I have list of dynamic created elements which when clicked fires a ajax request and displays the result. The problem is it works only when it is clicked twice. The first click on element doesn't work. Whereas the second click works perfectly. I don't understand the reason behind this. I did try unbind() but it didn't help

$("#profiles_name ul a").on('click',function(event){
        $.ajax({ 
  }
  });
  });.

I did try $("#profiles_name ul a").unbind().on('click',function(event).. It didnt work still.

Here is my dynamically created tag

<ul>
  <a href="javascript:myfunction(this)" data-value="20/20"><li>Frontend Dev</li></a>
  <li class="divider"></li>
</ul>

Also to keep in note that, For example if i have two dynamically created list, When i click on list 1(first time) it doesnt work list 1( second time) works. After page refresh, click on list 1(first time) doesn't work and click on list 2 (first time) works. i.e First click doesnt work irrespective of the dynamically created element.

Naveen Kumar
  • 1,476
  • 5
  • 28
  • 52

1 Answers1

1

Prefer to use event delegation:

$("#profiles_name").on('click', 'ul a', function() {
    $.ajax({
        // Your code here
    });
});

Event delegation:

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.

Dipiks
  • 3,818
  • 2
  • 23
  • 39
  • No , It didnt work – Naveen Kumar Jan 17 '17 at 12:09
  • Just keep in mind that performance can be effected by using `document`, all depends one how complex your situation is of course, most scenarios you wont notice any. Usually better to provide a more specific static element if you can. For example: `$("#profiles_name").on('click', 'ul a',function(event){` – musefan Jan 17 '17 at 12:09
  • @musefan You're absolutely right, I update my answer with your remark – Dipiks Jan 17 '17 at 12:11
  • @NaveenKumar Can you provide a better sample of your HTML/JS code so ? – Dipiks Jan 17 '17 at 12:12
  • http://codepen.io/anon/pen/EZNNej here is my code pen that has html and javascript function – Naveen Kumar Jan 17 '17 at 12:16
  • @NaveenKumar It seems that it is an error with your `href="javascript:myfunction(this)"`, -> `Uncaught ReferenceError: myfunction is not defined` – Dipiks Jan 17 '17 at 12:20
  • @GilleQ. that was for sample , you can see the codepen again , i changed it. There is no issue with it – Naveen Kumar Jan 17 '17 at 12:24
  • @NaveenKumar Add jQuery to your codePen (Settings, javascript -> add jquery). The only error I got from you codePen is `GET http://s.codepen.io/profiles/20/20?_=1484656054639 404 (Not Found)`. I do not know what data you are trying to retrieve from your server – Dipiks Jan 17 '17 at 12:29
  • There is no problem with the server side or ajax. THe problem is in the frontend. I really dont understand this – Naveen Kumar Jan 17 '17 at 12:31