Search code examples
javascripthtmlfetchdom-events

HTML Component That Is Fetched With JavaScript Not Responding To Click Event


I have an HTML component that is fetched when user clicks on a button. This component/modal is used to change a user's profile image (this is processed with PHP). The JavaScript fetch() happens with the following code:

var newProfileImageButton = document.getElementById('replace-profile-photo'),
    changeProfileImageWrapper = document.getElementById('change-profile-image-wrapper'),
    profileImageModalPath = "modals/change-profile-image.php";

newProfileImageButton.addEventListener('click', function(){

    fetch(profileImageModalPath)
        .then((response) => {
            return response.text();
        })
        .then((component)=>{
            changeProfileImageWrapper.innerHTML = component;
        })
        .catch((error => {console.log(error)}))

})

This fetched component includes a 'close' button should the user wish to close the modal and not update their profile image.

When I click the close button though nothing is happening. I have the script below - is the issue to do with the fact the Javascript has loaded before the component/modal is fetched? And if so how do I fix this? I guess I could just toggle display:none off and on for this component but would prefer to fetch it if possible.

Note: The button is responding to CSS hover events so I'm confident it's not an HTML / CSS markup issue.

// close button is part of the HTML component that is fetched 
var closeComponent = document.getElementById('form-close-x')

if (closeComponent) {
    closeComponent.addEventListener('click', function(){
         
        // Hide the main component wrapper so component disappears
        changeProfileImageWrapper.style.display = 'none';

    })
}

I've also tried using the following code, which I found in a similar question, but this doesn't work either (it was suggested this was a duplicate question).

var closeComponent = document.getElementById('form-close-x')

if (closeComponent) {
    closeComponent.addEventListener('click', function(e){

        if (e.target.id == 'form-close-x') {
            changeProfileImageWrapper.style.display = 'none';
        }
    })
}

Solution

  • Try this:

    // var closeComponent = document.getElementById('form-close-x') <-- remove
    // if (closeComponent) { <-- remove
        document.addEventListener('click', function(e){
            if (e.target.id === 'form-close-x') {
                changeProfileImageWrapper.style.display = 'none';
            }
        })
    //} <-- remove