Skip to content

Instantly share code, notes, and snippets.

@2aces
Created November 8, 2017 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2aces/dcb9aa8885bcd8ba6189518e8be97b73 to your computer and use it in GitHub Desktop.
Save 2aces/dcb9aa8885bcd8ba6189518e8be97b73 to your computer and use it in GitHub Desktop.
An experiment for cloning social buttons and insert them elsewhere in a WordPress page
function wp_social_buttons_cloner_scripts() {
wp_register_script( 'wp_social_buttons_cloner', $path_to_the_javascript_script, array(''), '0.1.0', true);
wp_register_script( 'wp_social_buttons_cloner');
};
add_action('wp_enqueue_scripts', 'wp_social_buttons_cloner_scripts');
'use strict';
/**
* @summary Clones social buttons and insert them elsewhere
*
* Clones social buttons and insert them elsewhere in the DOM after the window.load event.
* Can be used to clone anything else, in fact.
*
* @listens window.load
*
* @param string $sourceSelector a CSS3 element selector for the element to be cloned
* @param array $wrappersSelectors an array of CSS3 element selectors to append the cloned elements
* @returns voide
*/
function cloneSocialButtons( sourceSelector = '', wrappersSelectors = [] ) {
// get the source element
var originalButtons = document.querySelector( '#original-buttons' );
// if wrappersSelectors is empty or not-provided, bail and logs to console
if ( wrappersSelectors.length === 0) {
console.error('wrappersSelectors must be a non-empty array of CSS3 selectors');
return;
}
// for each item in wrappersSelectors array, clones the source element
wrappersSelectors.forEach( function( wrapper ){
// get the wrapper element in the DOM
var wrapper = document.querySelector( wrapper );
// for each wrapper in the array, clones the source element and appends it to wrapper
var clone = originalButtons.cloneNode( true );
wrapper.appendChild(clone);
});
}
// lazy load cloneSocialButtons on window.load event
if ( window.addEventListener ) {
window.addEventListener('load', cloneSocialButtons, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", cloneSocialButtons);
}
else {
window.onload = cloneSocialButtons;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment