Skip to content

Instantly share code, notes, and snippets.

@jpjuliao
Last active October 4, 2024 15:38
Show Gist options
  • Save jpjuliao/8bb5faa4a8d4a4bb6df6cd95fc15f5b6 to your computer and use it in GitHub Desktop.
Save jpjuliao/8bb5faa4a8d4a4bb6df6cd95fc15f5b6 to your computer and use it in GitHub Desktop.
Function to create and inject the WhatsApp button
// Function to create and inject the WhatsApp button
function injectWhatsAppButton(phone, href, logoUrl) {
try {
// Validate input parameters
if (!phone || !href || !logoUrl) {
throw new Error('Missing required parameters');
}
// Create the button element
const button = document.createElement('a');
button.href = href;
button.target = '_blank';
button.className = 'brz-cp-color8 link--external';
button.style.position = 'fixed';
button.style.bottom = '20px';
button.style.right = '20px';
button.style.backgroundColor = '#25D366';
button.style.borderRadius = '50%';
button.style.width = '60px';
button.style.height = '60px';
button.style.display = 'flex';
button.style.justifyContent = 'center';
button.style.alignItems = 'center';
button.style.boxShadow = '2px 2px 3px #999';
button.style.zIndex = '100000';
// Create the SVG element
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('class', 'brz-icon-svg align-[initial]');
svg.style.width = '30px';
svg.style.height = '30px';
// Create the use element to reference the external SVG
const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', logoUrl);
// Append elements
svg.appendChild(use);
button.appendChild(svg);
// Add the button to the body
document.body.appendChild(button);
console.log('WhatsApp button successfully injected');
} catch (error) {
console.error('Error injecting WhatsApp button:', error);
}
}
// Function to check if the DOM is loaded
function domReady(callback) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback);
} else {
callback();
}
}
// // Usage example (you would call this with your specific parameters)
// domReady(() => {
// try {
// const phone = '573215197850';
// const href = `https://wa.me/${phone}`;
// const logoUrl = 'https://www.stemcellscolombia.co/icon/16703871/glyph/logo-whatsapp.svg#nc_icon';
// injectWhatsAppButton(phone, href, logoUrl);
// } catch (error) {
// console.error('Failed to inject WhatsApp button:', error);
// }
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment