Event-delegation must be used to make events work after inserting DOM elements (i.e Ajax response) but what about basic JS instructions?
As you will see, all the instructions are sorted by affected PHP page (to update and improve the code more easily, and not to repeat the same instructions several times).
Here, I want to test if a given class exists. This class doesn’t exist when the JS file is loaded, but will be after inserting the AJAX response.
Code 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,
if ( $('.className').length) {
$('.button-navbar').show(); }
doesn’t seem to be executed, whereas the class now exists.
Do you have a solution which does not break the JS file architecture ?
That code isn’t an event handler and doesn’t set up any sort of permanent rule. It’s just straight procedural code, there’s no reason it would get called again automatically. At the time it was executed, there was on such class. Adding a class will not make the code execute again.
However, you can manually do that check in both places (at the beginning, and in the ajax callback). To avoid duplication, you can put the shared functionality into an actual function:
And then call it in the ajax callback too:
Sidenote: there is also a solution to this problem using jQuery.live(), but I didn’t include it because I think the above is better, in part for efficiency reasons.