Twentyonehundred Twentyonehundred - 24 days ago 5
Javascript Question

JQuery - Click listener not firing when trigger classes are swapped

I have a jQuery on click listener that looks for class 'install-plugin'.

When clicked, it changes the class (via jQuery) to 'delete-plugin'.

And vice versa, so there is a listener for 'delete-plugin' that, when clicked, changes the class to 'install-plugin'.

The problem I have is that this only works once, and although I can see the classes have updated on the page correctly, jQuery doesn't seem to see that and still fires the original listener.

(The ajax is necessary for the intended, extended functionality). Is it possible to have jQuery always be up to date with what's on the page without hard refreshing it?

$(document).ready(function() {
$('.install-plugin').click(function() {
var id = $(this).attr('id');
var postData = {
action : 'install_plugin',
}
$.ajax({
method: 'POST',
url: "/wp-admin/admin-ajax.php",
data: postData,
success: function(response) {
$('#'+id).text('Delete');
$('#'+id).removeClass('install-plugin');
$('#'+id).addClass('delete-plugin');
}
});
})

$('.delete-plugin').click(function() {
var id = $(this).attr('id');
var postData = {
action : 'delete_plugin',
}
$.ajax({
method: 'POST',
url: "/wp-admin/admin-ajax.php",
data: postData,
success: function(response) {
$('#'+id).text('Install');
$('#'+id).removeClass('delete-plugin');
$('#'+id).addClass('install-plugin');
}
});
})
});

Answer

Use the 'on' syntax, e.g. $(selector).on('click', function(event){....}) for dynamically changed elements.

.click() fails after dom change

Comments