1

I have two click functions: one targets td.default and the second td.clicked. Both changes the class attribute to either 'clicked' or 'default' (and updates the text in the cell). The classes are getting changed from the first click function but the second click function that looks for td.click doesn't find it's target.

$("td.default").click(function() {
    $(this).attr('class','clicked');
    $(this).text("monkey");
    $("#ouput").append("td.default clicked<br/>"); //reporting message
});
$("td.clicked").click(function() {
    $(this).attr('class','default');
    $(this).text("empty");
    $("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
Jawa
  • 99
  • 2
  • 12

3 Answers3

3

When you bind a click handler, you are binding to the element. Changing the class of the element doesn't change that handler that you've bound to it. If you want that behavior, you'll need to use on() with event delegation. See on(), especially the section about "direct and delegated events".

Demo Click Here :

$(document).on('click', "td.default", function() {
    $(this).attr('class','clicked');
    $(this).text("monkey");
    $("#ouput").append("td.default clicked<br/>"); //reporting message
});
$(document).on('click', "td.clicked", function() {
    $(this).attr('class','default');
    $(this).text("empty");
    $("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
Jason P
  • 26,984
  • 3
  • 31
  • 45
  • Bruvooo, Add this one as well `:)` rest mine was same so deleted my post! http://stackoverflow.com/questions/5874652/prop-vs-attr `:)` – Tats_innit Oct 24 '13 at 20:47
2

Use delegation instead

$("table").on("click", "td.default", function() {
    $(this).attr('class','clicked');
    $(this).text("monkey");
    $("#ouput").append("td.default clicked<br/>"); //reporting message
});
$("table").on("click", "td.clicked", function() {
    $(this).attr('class','default');
    $(this).text("empty");
    $("#ouput").append("td.clicked clicked<br/>"); //reporting message
});

Delegation would handle the dynamic changes on the nodes v/s .click(), which would not rebind dynamically modified nodes. Read more on delegation using on here

karthikr
  • 97,368
  • 26
  • 197
  • 188
1

That seems like a lot of work, would it be easier to do it this way?

$('td.default,td.clicked').on('click', function() {
    $(this).toggleClass('default').toggleClass('clicked').text(
        $(this).text() === 'empty' ? 'monkey' : 'empty'
    );
});

made a fiddle: http://jsfiddle.net/filever10/PdjMX/

FiLeVeR10
  • 2,155
  • 1
  • 12
  • 13