diff --git a/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js b/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js index d2dda892b13..3fb1e525504 100644 --- a/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js +++ b/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js @@ -162,7 +162,7 @@ } }); $('.related-widget-wrapper select').trigger('change'); - $('.related-lookup').click(function(e) { + $('body').on('click', '.related-lookup', function(e) { e.preventDefault(); var event = $.Event('django:lookup-related'); $(this).trigger(event); diff --git a/django/contrib/admin/static/admin/js/change_form.js b/django/contrib/admin/static/admin/js/change_form.js index 994b52394e2..4797383b30a 100644 --- a/django/contrib/admin/static/admin/js/change_form.js +++ b/django/contrib/admin/static/admin/js/change_form.js @@ -4,7 +4,7 @@ 'use strict'; $(document).ready(function() { var modelName = $('#django-admin-form-add-constants').data('modelName'); - $('.add-another').click(function(e) { + $('body').on('click', '.add-another', function(e) { e.preventDefault(); var event = $.Event('django:add-another-related'); $(this).trigger(event); diff --git a/docs/internals/contributing/writing-code/javascript.txt b/docs/internals/contributing/writing-code/javascript.txt index 25a46695c39..3d10c48f003 100644 --- a/docs/internals/contributing/writing-code/javascript.txt +++ b/docs/internals/contributing/writing-code/javascript.txt @@ -24,6 +24,12 @@ Code style JSHint will be run when you run the JavaScript tests. We also recommended installing a JSHint plugin in your text editor. +* Where possible, write code that will work even if the page structure is later + changed with JavaScript. For instance, when binding a click handler, use + ``$('body').on('click', selector, func)`` instead of + ``$(selector).click(func)``. This makes it easier for projects to extend + Django's default behavior with JavaScript. + .. _javascript-patches: JavaScript patches