When adding content dynamically, it is necessary to use an event handler for a parent element using on(). However, I am facing an issue where the class added with addClass on dynamically generated content disappears immediately.
Let's take a look at the relevant part of the HTML code:
<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>
Below is the code snippet responsible for adding 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();
});
However, when clicking on one of the dynamically created elements, the class is only temporarily added for a brief moment. Here is the specific code causing the issue:
$('#training_management_categories_items').on('click', '.training_management_categories_list_a', function () {
$(this).addClass('categories_selected'); // DOESN'T WORK
alert( $( this ).text() ); // THIS WORKS
});
The CSS code for the elements looks fine and nothing seems out of place. The issue persists even after checking the CSS properties. Any ideas on what might be causing this behavior?
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;
}
It is worth mentioning that jquery-1.10.2.js is being used in this scenario.