I am using the ClipboardJS library to copy text that is attached to a button using the data-clipboard-text
attribute. I am also using jQuery's .load()
function to dynamically pull in HTML content. This content includes copies of the Copy text buttons. When the 'fresh' buttons are loaded using jQuery, the buttons no longer have an event bound to them. I have attached my current working code below.
Is there a way to re-bind the events to the buttons after the dynamic content is loaded? A vanilla JS solution would be preferable.
jQuery load function
jQuery(document).ready(function(e) {
// AJAX .load function for sendout post content
e( ".sendout-link" ).click(function() {
var post_url = e( this ).attr( "href" );
e( "#sendout-container" ).html( '<div class="loading">Loading...</div>' );
e( "#sendout-container" ).load( post_url, function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
e( "#sendout-container" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
return false;
});
});
ClipboardJS code
var btns = document.querySelectorAll('.copy-button');
var clipboard = new ClipboardJS(btns);
clipboard.on('success', function(e) {
e.trigger.textContent = 'URL Copied';
e.trigger.setAttribute('disabled', true);
window.setTimeout(function() {
e.trigger.textContent = 'Copy URL';
e.trigger.removeAttribute('disabled');
}, 5000);
});
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
You can bind the events during the dynamic load()
process.
function bindCopy(){
var btns = document.querySelectorAll('.copy-button');
var clipboard = new ClipboardJS(btns);
clipboard.on('success', function(e) {
e.trigger.textContent = 'URL Copied';
e.trigger.setAttribute('disabled', true);
window.setTimeout(function() {
e.trigger.textContent = 'Copy URL';
e.trigger.removeAttribute('disabled');
}, 5000);
});
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
}
jQuery(document).ready(function(e) {
// AJAX .load function for sendout post content
e( ".sendout-link" ).click(function() {
var post_url = e( this ).attr( "href" );
e( "#sendout-container" ).html( '<div class="loading">Loading...</div>' );
e( "#sendout-container" ).load( post_url, function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
e( "#sendout-container" ).html( msg + xhr.status + " " + xhr.statusText );
}else{
bindCopy(); //each time content is loaded
}
});
return false;
});
bindCopy(); //first time
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With