How to Reinitialize JavaScript Functionality for Dynamically Added Elements Without Duplicate Event Listeners?

I am developing a social media platform using Django for the backend and a purchased HTML template from ThemeForest for the frontend. The template was built using React and then exported to plain HTML, CSS, and a large JavaScript file (over 26,000 lines). I am encountering issues when trying to dynamically add new elements to the DOM and reinitialize the JavaScript functionality for these new elements.

Issue:

The large JavaScript file contains all the necessary functionality to handle UI interactions, animations, and event listeners. Initially, when the page loads, everything works fine. However, when I dynamically add new posts (e.g., when the user scrolls to the bottom of the page to load more posts), the new elements do not have the JavaScript functionality applied to them.

To address this, I wrapped the entire code from the large JavaScript file into a function called reinitialize. After adding new elements, I call this reinitialize function to apply the necessary JavaScript functionality to the new elements. This works, but it introduces a significant issue: duplicate event listeners are added to existing elements, causing unexpected behavior (e.g., click events firing multiple times).

Scenario:

Initial Page Load:

On initial page load, the template’s JavaScript file initializes all elements correctly.

<div id="posts-container">
    <div class="post">
        <!-- Post content here -->
        <button class="like-button">Like</button>
    </div>
</div>

<script src="/static/js/large-file.js"></script>
<script>
    // Initial call to reinitialize all elements
    reinitialize();
</script>

Adding New Posts Dynamically:

When the user scrolls to the bottom, new posts are fetched and added to the DOM.

function loadMorePosts() {
    fetch('/load-more-posts')
        .then(response => response.json())
        .then(data => {
            data.posts.forEach(post => {
                let postElement = document.createElement('div');
                postElement.className = 'post';
                postElement.innerHTML = `
                    <!-- Post content here -->
                    <button class="like-button">Like</button>
                `;
                document.getElementById('posts-container').appendChild(postElement);
            });

            // Call reinitialize to apply JavaScript functionality to new elements
            reinitialize();
        });
}

// Event listener for scrolling to the bottom
window.addEventListener('scroll', () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        loadMorePosts();
    }
});

Problem:

Each time reinitialize is called, it adds duplicate event listeners to existing elements, leading to issues such as event-listeners cancelling each-other out which won’t make the button click, but I react to a post which will call the reinitialize() function again to format the reactions correctly, the button click will work because there will be three eventlistener attached to it, two cancel eachother out and the third one take over (like not really cancel, like toggle).

Question:

How can I reinitialize the JavaScript functionality for dynamically added elements without causing duplicate event listeners and other conflicts? Is there a more efficient way to handle this scenario?

Attempts and Considerations:

  • MutationObserver: I considered using MutationObserver to detect new elements, but I still need to reapply the functionality without causing duplicates.
  • Selective Reinitialization: Ideally, I would like to reinitialize only the newly added elements, but the current structure of the large JavaScript file makes this challenging.

Example Code:

Here is the code snippet illustrating the problem:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Social Media Platform</title>
</head>
<body>
    <div id="posts-container">
        <div class="post">
            <!-- Post content here -->
            <button class="like-button">Like</button>
        </div>
    </div>
    
    <script src="/static/js/large-file.js"></script>
    <script>
        // Initial reinitialization
        reinitialize();

        function loadMorePosts() {
            fetch('/load-more-posts')
                .then(response => response.json())
                .then(data => {
                    data.posts.forEach(post => {
                        let postElement = document.createElement('div');
                        postElement.className = 'post';
                        postElement.innerHTML = `
                            <!-- Post content here -->
                            <button class="like-button">Like</button>
                        `;
                        document.getElementById('posts-container').appendChild(postElement);
                    });

                    // Call reinitialize to apply JavaScript functionality to new elements
                    reinitialize();
                });
        }

        window.addEventListener('scroll', () => {
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
                loadMorePosts();
            }
        });
    </script>
</body>
</html>

Any advice or solutions to efficiently reapply the JavaScript functionality to newly added elements without causing duplicates would be greatly appreciated. Thank you!

This is the complicated javascript here: app.min.js

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật