How can I hide a div that I've just added with a click?

I’m appending some HTML to my button on a click, like this:

jQuery(document).ready(function($) {
    $('#sprout-view-grant-access-button').on('click', function(e) {
        $(this).toggleClass('request-help-cta-transition', 1000, 'easeOutSine');
        var callback = $(e.currentTarget).attr('data-grant-access-callback');
        var wrapper = $('.dynamic-container');
        console.log(wrapper);

        if( typeof window[callback] !== 'function') {
            console.log('Callback not exist: %s', callback);
        }

        var already_exists = wrapper.find('.main-grant-access');
        console.log(already_exists);

        if( already_exists.length ) {
            already_exists.remove();
        }

        var markup = $(window[callback](e.currentTarget));
        wrapper.append(markup);

    });
});

function generate_grant_access_container_markup() {
    var contact_data_array = contact_data;

    var template = jQuery('#template-sprout-grant-access-container')

    return mustache(template.html(), {
        test: 's'
    });
}

As per the code, whatever comes from generate_grant_access_container_markup will be put inside dynamic-container and shown.

My problem is that, the newly added code just doesn’t wanna dissapear upon clicking (toggle) of the button once again.

Here’s my syntax / mustache template:

<script type="template/mustache" id="template-sprout-grant-access-container">
    <p class="main-grant-access">{{{test}}}</p>
</script>

And here’s the container:

<div class="button-nice request-help-cta" id="sprout-view-grant-access-button" data-grant-access-callback="generate_grant_access_container_markup">
Grant Devs Access
    <div class="dynamic-container"></div>
</div>

I understand that the click event only knows about items that are in the DOM at the moment of the click, but how can I make it aware of everything that gets added after?

67 thoughts on “How can I hide a div that I've just added with a click?”

Leave a Comment