JSFiddle - React, Tailwind, and code Playground
by ckissi
JavaScript
(function() {
// Configuration API endpoint
const CONFIG_API_URL = 'https://api.yourserver.com/popup-config';
const CACHE_DURATION = 3600000; // 1 hour in milliseconds
// Function to fetch config from API or cache
async function getConfig() {
const cachedConfig = localStorage.getItem('stickyPopupConfig');
const cachedTimestamp = localStorage.getItem('stickyPopupConfigTimestamp');
if (cachedConfig && cachedTimestamp) {
if (Date.now() - parseInt(cachedTimestamp) < CACHE_DURATION) {
return JSON.parse(cachedConfig);
}
}
try {
const response = await fetch(CONFIG_API_URL);
if (!response.ok) throw new Error('Network response was not ok');
const config = await response.json();
localStorage.setItem('stickyPopupConfig', JSON.stringify(config));
localStorage.setItem('stickyPopupConfigTimestamp', Date.now().toString());
return config;
} catch (error) {
console.error('Error fetching config:', error);
return cachedConfig ? JSON.parse(cachedConfig) : {
"link": "https://example.com",
"text": "Check out this amazing site!",
"position": "bottom-right",
"styles": {
"backgroundColor": "#f0f0f0",
"borderColor": "#ccc",
"textColor": "#333",
"linkColor": "#0066cc"
}
};
}
}
// Function to create and inject styles
function injectStyles(config) {
const style = document.createElement('style');
style.textContent = `
.sticky-popup {
position: fixed;
${config.position.includes('bottom') ? 'bottom' : 'top'}: 20px;
${config.position.includes('right') ? 'right' : 'left'}: 20px;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
...