Jackson Cunningham
Jackson Cunningham

Reputation: 5073

How can I fire a jQuery click event for dynamic content (modal)

I followed the instructions on this answer to copy a URL when user clicks a button. Seems to work fine, except when I move my button into a modal window. I lose my click event handler.

function copyTextToClipboard(text) {
    [...] // working implementation
}

$(function() {
    var currentPostUrl = window.location.href + "?ref=blogshare"
    var currentPostTitle = $('.post-title').text().trim();

    $('.js-copy-bob-btn').on('click', function(event) {
        copyTextToClipboard(currentPostUrl);
        console.log('copied')
    });

    $('#myModal').appendTo("body") 
});

Here's my HTML:

<!-- Modal -->

<div id="myModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" type="button" data-dismiss="modal">×</button>
            </div>

            <div class="modal-body">
                <div class="row modal-icons">
                    <div class="col-xs-5 text-center">
                        <a class="copy-url js-textareacopybtn" title="Step 2: Copy URL Button">
                            <h3>Copy Shareable Link</h3>
                        </a>

                       <-- THE BELOW BUTTON DOES NOT WORK AS DESIRED  -->  

                       <button class="js-copy-bob-btn">Copy Url</button>
                   </div>
               </div>
           </div>           
       </div>
   </div>
</div>

    <-- THE BELOW BUTTON WORKS AS DESIRED  (NO MODAL)-->

<button class="js-copy-bob-btn">Copy Url</button>

Where am I going wrong? Why does the second button (outside of modal) work but not the first button?

Upvotes: 5

Views: 2709

Answers (1)

scniro
scniro

Reputation: 16979

I'm guessing your modal is dynamic markup that is injected one way or another. There are various modal flavors/libraries out there, but my suspicions are that your dynamic content does not have the proper event handlers for this. jQuery provides a way for us to do this with delegate()

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

I made a very simple example which demonstrates this specific scenario. I am crafting and injecting dynamic content, with a button, wired to click handlers via .on() and .delegate(). Observe the following example and differences between the two...

// faux modal
$('body').append('<div class="modal"><button class="js-copy-bob-btn">Copy Url</button></div>');

// does not work
$('.js-copy-bob-btn').on('click', function(event) {
    console.log('copied via on');
});

// works - dynamic content
$('body').delegate('.js-copy-bob-btn', 'click', function() {
    console.log('copied via delegate');
});

JSFiddle Link - working demo

Upvotes: 5

Related Questions