1

I have wasted 1 hour on api.jquery.com and my script to identify the problem but still unable.

Here is my script.js

// DOM ready

$(function(){

    // gets categories from server
    $.post("category.php", function(data) {
        $("#category ul").html(data);
    });

    // tests click event
    $("a").click(function(evt) {
        alert("Handler for .click() called.");
        evt.preventDefault();
    });

});

In index.php there are 4 anchor tags first three loaded from server as you can see in script and the last on is preloaded(static)(not loaded from server). Problem is that I have selected all anchor elements in jQuery selector as you can see in script but my event is only working with the last anchor tag which is pre-loaded. What is wrong ? Why the event is not working with the first three anchor tags ?

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
Yousuf Memon
  • 4,638
  • 12
  • 41
  • 57
  • Because you are binding the event handler **before** the other `a` elements exist. – Felix Kling Nov 09 '12 at 07:41
  • @FelixKling so how to overcome it ? – Yousuf Memon Nov 09 '12 at 07:42
  • 1
    $(document).on('click','a',function(event){}) – Rene Koch Nov 09 '12 at 07:43
  • 1
    http://stackoverflow.com/questions/5772018/jquery-add-event-handler, http://stackoverflow.com/questions/12065329/jquery-adding-event-listeners-to-dynamically-added-elements, http://stackoverflow.com/questions/10488861/automatically-add-an-event-handler-to-a-newly-created-element-using-jquery. – Felix Kling Nov 09 '12 at 07:43

3 Answers3

5

try using on

   $('body').on('click', 'a', function(evt) {
     alert("Handler for .click() called.");
     evt.preventDefault();
   });
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
4

Try:

$(document).on('click', 'a', function (){
    //do something
});

This will bind your handler to all anchor tags that currently exist and any that will be added dynamically in the future.

Yatrix
  • 13,361
  • 16
  • 48
  • 78
1
$(function(){

// gets categories from server
$.post("category.php", function(data) {
   $("#category ul").html(data);

// tests click event
   $("a").click(function(evt) {
      alert("Handler for .click() called.");
      evt.preventDefault();
  });
 });
});

you have to wait till the ajax post request is ready!

Greetings!

Mic
  • 523
  • 6
  • 18