2

This is my code:

$('.add').click(function(){ $('#test').append("<div class='tab selected'>TEST</div>"); }); $('.tab').click(function(){ $('.tab').removeClass('selected').addClass('unselected'); $(this).removeClass('unselected').addClass('selected'); }); <input type='button' value='add' class='add' /> <div id='test'> <div class='tab unselected'>TEST</div> </div> 

This is my issue:

When I click the .tab div that was already defined in html, the function works fine. But, if I add another .tab div using the .add input, the function does not work.

What exactly am I doing wrong here?

3 Answers 3

4

The event handlers are bound to the element that exist at the time they are executed. In case of dynamic content updates, your bet is to either rebind the handler or use delegated events like below.

$('#test').on('click', '.tab', function(){ $('.tab').removeClass('selected').addClass('unselected'); $(this).removeClass('unselected').addClass('selected'); }); 

Or you can rebind like below,

$('.add').click(function(){ $('.tab').removeClass('selected'); //comment from @MG_Bautista var newTab = $('<div />') .addClass('tab selected') .click(tabFx) .text('Test'); $('#test').append(newTab); }); $('.tab').click(tabFx); function tabFx(){ $('.tab').removeClass('selected').addClass('unselected'); $(this).removeClass('unselected').addClass('selected'); } 
Sign up to request clarification or add additional context in comments.

2 Comments

@Vega if you clic two or more times, the new tabs showed selected, the selection is unique, add $('.tab').removeClass('selected') before the line $('.tab').append(newTab);... @user1885099 read the comment...
@MG_Bautista Must be a bug from original code, fixed it though. Thanks
0

use either "live" or "on"... if you are referencing jquery 1.7 or less then live will work....if you are using latest jquery use "on"

$('#test').on('click', '.tab', function(){ $('.tab').removeClass('selected').addClass('unselected'); $(this).removeClass('unselected').addClass('selected'); }); 

or

$('#test').live('click', '.tab', function(){ $('.tab').removeClass('selected').addClass('unselected'); $(this).removeClass('unselected').addClass('selected'); }); 

1 Comment

Even for older versions, .delegate is recommended over .live.
0

Use this...

$('.add').click(function(){ $('.tab').removeClass('selected').addClass('unselected'); $('#test').append("<div class='tab selected'>TEST</div>"); }); $('#test').on('click', '.tab', function(){ $('.tab').addClass('unselected'); $(this).removeClass('unselected'); $('.tab').removeClass('selected'); $(this).addClass('selected'); }); 

And see DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.