0

I have two lists with different classes,

<li><a href='#' class="cls1" name="X">blah</a></li> <!-- Click to load a cls2 item -->
<li><a href='#' class="cls1" name="Y">blah</a></li>

<li><a href='#' class="cls2" name="A">blah</a></li>
<li><a href='#' class="cls2" name="B">blah</a></li>

I have this script to handle click function.

$(function(){
$('.cls1').click(function(e){
    alert('cls1 clicked');
    e.preventDefault();
    ... //ajax call to load cls2 items
    });
$('.cls2').click(function(e){
    alert('cls2 clicked');
    e.preventDefault();
    ...
    });
)};

Important The cls2 class items are loaded by an ajax function called in cls1 click function

The cls1 items click function works fine, but when i click any cls2 item, nothing happens.

Is there any problem by adding it after the whole page loads? (by ajax call)

Another issue I notted is that if i refresh the page, and i change the cls1 class to cls2 in the code (using chrome console) the css changes correctly but it still doing the cls1 click function. Why???

Any Idea? I have tried to change the click function order, change the class names, even with another jquery library... (I am using v1.11.1)

Issue example here: http://jsfiddle.net/f7o5y3ek/

Alex Lord Mordor
  • 2,890
  • 7
  • 27
  • 47

2 Answers2

2

If I understand correctly, your issue is you're adding event listeners to elements that don't exist yet. You have to add the .cls2 listeners after those elements are created by your ajax call.

Something like this (converted form Coffeescript, sorry):

$.ajax("path/to/call", {
  success: (function(_this) {
    return function() {
      return _this.addItems;
    };
  })(this)
});

({
  addItems: function() {
    // add new items & listeners here
  }
});

Alternately, and better I think, is to use event delegation, like this:

$( "parent_selector" ).on( "click", ".cls2", function( event ) {
    event.preventDefault();
    console.log( "clicked!" );
});
steel
  • 11,883
  • 7
  • 72
  • 109
2

Add the cls2 click handler to the ajax success part or try with this:

$(document).on('click, '.cls2', function(e){
    alert('cls2 clicked');
    e.preventDefault();
    ...
    });
)};
Salil Dabholkar
  • 622
  • 3
  • 7