1

Why does jQuery not seem to work when I change my name class name to new one. However CSS works perfectly:

$(document).ready(function(){

    $('.span_new_msgs').click(function(){
         $(this).removeClass('span_new_msgs').addClass('span_msgs');
   });

    $('.span_msgs').click(function(){   
        alert("hello"); // do something     
    });
});
halfer
  • 19,824
  • 17
  • 99
  • 186
niko
  • 9,285
  • 27
  • 84
  • 131

2 Answers2

3

The problem is that the class of each span is only taken into account at the time when your event handlers are attached. If that class changes later the handlers do not change to reflect that.

One solution is to use delegated events:

$(document).on("click", '.span_new_msgs', function(){
     $(this).removeClass('span_new_msgs').addClass('span_msgs');
});

$(document).on("click", '.span_msgs', function(){
     alert("hello");
});

This way the handlers are attached to the document element and the class of the click target is inspected at the time of the click to determine what happens.

However, personally I 'd be more inclined to do it somewhat differently: use only one class and store the "is new" flag somewhere else, for example in an HTML5 data attribute:

$(document).on("click", '.span_msgs', function(){
    var $this = $(this);
    if ($this.attr('data-new')) {
        $this.removeAttr('data-new');
    }
    else {
        alert("hello");
    }
});

With this scheme a "new" message span would be <span class="span_msgs" data-new>...</span>, while an "old" one would be missing the data-new attribute.

You could easily select elements with CSS selectors based on the presence of the attribute or not; the only difference is that there is only one class to consider when talking about message spans.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

To access an element that has a different class name from when the page loaded, use the on function instead.

$(document).on('click', '.span_new_msgs', function(){

})
Zevi Sternlicht
  • 5,399
  • 19
  • 31