0

I was once learned it is "better" to limit the use of global selectors. I tried it in the code below, but it doesn't work because the content (flat HTML) is loaded trough AJAX. The browser now has no clue what $(".item") is, because it is not loaded yet. What is the best way to solve this? Use a global selector like I did in the last snipper, or something else?

 export default class overview {
    
        constructor(el) {
            this.loadOverview(el);
        }
    
        loadOverview(el) {
            const $this = $(el),
                overview = $('.js-overview', $this),
                item = $('.js-item', $this)
    
    
            // Fetch content
            $.ajax({
                url: "URL",
                type: 'GET',
                success: function (data) {
                    $(overview).append(data);
                }
            });
            
            $(".item").click(function() {
                // Do something doesn't work
            }
        }

Clicking on item now doesn't do anything, because the item can't be found. When i change it to

    $body.on('click', '.item', function () {
        // Do something works
    });
mat
  • 1,619
  • 1
  • 15
  • 25
  • So basically I am doing the right thing already? – mat Sep 06 '21 at 10:37
  • 1
    Yes, that is correct. `$(".item").click` only adds the event listeners for the `.item` elements that are currently in the DOM. `$body.on('click', '.item', function` listens for a clicks on and inside the `body` element and only does something whenever the clicked element is `.item`. This also accounts elements that are dynamically added or removed as the event listener is not placed on the added or removed elements themselves. – Emiel Zuurbier Sep 06 '21 at 10:42

0 Answers0