I know that if I add content dynamically I have to use an event handler for a parent element using on(). But when I use addClass on dynamically added content the class immediately disappears.
Here's the relevant part of HTML (just to make sure I don't missed typos):
<div id="training_management_categories_items">
<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul">
</ul>
</div>
Here's the code that adds the dynamic elements:
function GetCategories()
{
var url = './ajax/training_management_data.php';
$('#training_management_categories_items').html('<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul"></ul>');
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
<a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_all">All</a> \
</li> \
');
$.ajax({
url: url,
type: "POST",
data: "action=get_categories",
dataType: 'json',
success: function (data) {
$.each(data, function(index, data) {
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
<a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_'+data.id+'">'+data.name+'</a> \
</li> \
');
});
}
});
}
$(document).ready(function() {
GetCategories();
});
But when I click the element the class is added for just like 0.1 seconds (had to switch the background-color for .categories_selected to red to see it) and I don't get why.
$('#training_management_categories_items').on('click', '.training_management_categories_list_a', function () {
$(this).addClass('categories_selected'); // DOESN'T WORK
alert( $( this ).text() ); // THIS WORKS
});
So if I click on one of the dynamically created elements it shows the text (for example "All" which is not fetched from php but you get the idea) but doesn't permanently add the class.
And just for me making ABSOLUTE sure I didn't miss anything really really stupid, here's the CSS:
a.training_management_categories_list_a {
text-decoration:none;
display:block;
background-image:url("img/icons/folder.png");
background-size:16px 16px;
padding-left:25px;
background-repeat:no-repeat;
font-size:9pt;
background-position:4px 2px;
height:20px;
padding-top:2px;
}
a.training_management_categories_list_a:hover {
background-color:#aaa;
}
a#training_management_categories_list_a_all {
font-weight:bold;
}
a.categories_selected {
background-color:#aaa !important;
}
Am I missing something here?
Edit: using jquery-1.10.2.js
return falsefrom the event handler or callevent.preventDefault()after receiving theeventparameter in the handler:hoverstyle gets in the way.