jQuery Click Function not Working on Class

javascript, jquery

Solution

If the game pieces are added after the page load (i.e. by clicking a button) you need to use event delegation by using jquery `.on()`

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.

$(myContainer).on('click', '.gamePiece', function(){
  $(this).addClass("toggled");
});

Problem

So I have a bunch of game pieces that I want to be clickable. If I add a click function to a button I get the desired result, but when I add it to the game piece class, it fails to work. Here is an example that works fine on jsfiddle, but not when I use it in my script: http://jsfiddle.net/sLt7C/ Here is what I want to do on my page: ``` $('.gamePiece').click(function(){ $('.gamePiece').addClass("toggled"); }); ``` This doesn't work, but if I switch the identifier to a button on the page it does work: ``` $('#btn_AddClass').click(function(){ $('.gamePiece').addClass("toggled"); }); ``` What could be causing this to fail? Not sure if this has any impact on what could be causing it to fail, but the "game pieces" are span elements that are generated after clicking a "New Game" button. Here is a fiddle showing more code http://jsfiddle.net/sLt7C/4/ For further clarification: This doesnt work ``` $('.gamePeice').click(function(){ $(this).addClass("toggled"); }); ``` This works ``` $('#btn_addClass').click(function(){ $('.gamePeice').addClass("toggled"); }); ```

Original source

Related problems