After inserting DOM elements (such as an AJAX response), event-delegation is necessary to ensure that events work properly. But what about basic JavaScript instructions?
All instructions are organized by affected PHP page to simplify code updates and avoid repetition. I want to test the existence of a specific class that is added dynamically after the JS file is loaded.
Example:
// NAVBAR.PHP
if ($('.className').length) {
$('.button-navbar').show(); }
/* FOOTER.PHP
.... */
// VIEW_NEWS.PHP
$('.ajax_wrapper').on('click', '#view_news tr', function() {
var id = $(this).attr("id");
var get_news_request = $.ajax({type: "GET", url: "view_news.php", data: {news_id: id}, dataType: "html"});
get_news_request.done(function(html) {
$('.ajax_wrapper').hide('slide', {direction: 'right'}, function(){
$('.ajax_wrapper').empty();
$('.ajax_wrapper').hide().html(html);
$('.ajax_wrapper').show('slide');
});
});
get_news_request.fail(function(jqXHR, textStatus, errorThrown) {
alert( "Request failed: " + textStatus + " " + errorThrown );
});
});
Unfortunately, the condition shown below is not being executed even though the class now exists:
if($('.className').length) {
$('.button-navbar').show(); }
Do you have a solution that does not disrupt the overall structure of the JS file?