cgpa2.17
cgpa2.17

Reputation: 319

selected tab jquery not working with appended elements

I surf through other examples of how to highlight current / selected tab on lists, the logic is very simple and direct, which is

    $('li').click(function (){      
$('li').not(this).removeClass('active').addClass('list');
}); 

however the new element which I appended via append method of jquery didn't response to the call.. only the existed li tag can be manipulated.. I wonder..

demo fiddle

Upvotes: 1

Views: 97

Answers (4)

Mihai Matei
Mihai Matei

Reputation: 24276

$('ul#task-group').on('click','li',function (){
  // do something
});

Upvotes: 0

Ashis Kumar
Ashis Kumar

Reputation: 6544

You need to again run those javascript code to bind the click event on the new li tags after appending them. You can do so by just some changes to the code and call that code after append operation.

JS Code:

function BindClickEvents() {
    $('li').unbind('click').bind('click',function (){      
       $('li').not(this).removeClass('active').addClass('list');
    });
  }

Now you need to call this method on body load / document ready once and then again after any append operation. The unbind is needed to remove all previously binding which can trigger multiply click events.

Upvotes: 0

drip
drip

Reputation: 12943

Change click event like so:

$(document).on( 'click', 'li', function (){      
    $('li').not(this).removeClass('active').addClass('list');
});

JSFiddle

Upvotes: 1

Tomer
Tomer

Reputation: 17930

click will not work on dynamically added elements, only on elements that are on the page when the click was called.

You need to use the on method.

Something like:

$('ul').on('click','li',function(){//your logic here})

Upvotes: 0

Related Questions