fix: Rename Assets/css to Assets/Css, Assets/js to Assets/Js in git
Windows case-insensitive but Linux case-sensitive. Git was tracking lowercase, causing 404s on server. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
545
Assets/Js/accessibility.js
Normal file
545
Assets/Js/accessibility.js
Normal file
@@ -0,0 +1,545 @@
|
||||
/**
|
||||
* Accessibility JavaScript
|
||||
*
|
||||
* Mejoras de accesibilidad para navegación por teclado, gestión de focus,
|
||||
* y cumplimiento de WCAG 2.1 Level AA.
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Inicializar todas las funciones de accesibilidad
|
||||
*/
|
||||
function init() {
|
||||
setupSkipLinks();
|
||||
setupKeyboardNavigation();
|
||||
setupFocusManagement();
|
||||
setupAriaLiveRegions();
|
||||
announcePageChanges();
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip Links - Navegación rápida al contenido principal
|
||||
* Permite a usuarios de teclado y lectores de pantalla saltar directamente al contenido
|
||||
*/
|
||||
function setupSkipLinks() {
|
||||
const skipLinks = document.querySelectorAll('.skip-link');
|
||||
|
||||
skipLinks.forEach(function(link) {
|
||||
link.addEventListener('click', function(e) {
|
||||
const targetId = this.getAttribute('href');
|
||||
const targetElement = document.querySelector(targetId);
|
||||
|
||||
if (targetElement) {
|
||||
e.preventDefault();
|
||||
|
||||
// Hacer el elemento focusable temporalmente
|
||||
targetElement.setAttribute('tabindex', '-1');
|
||||
|
||||
// Enfocar el elemento
|
||||
targetElement.focus();
|
||||
|
||||
// Scroll al elemento si está fuera de vista
|
||||
targetElement.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start'
|
||||
});
|
||||
|
||||
// Remover tabindex después del focus para no interferir con navegación normal
|
||||
targetElement.addEventListener('blur', function() {
|
||||
targetElement.removeAttribute('tabindex');
|
||||
}, { once: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Navegación por Teclado Mejorada
|
||||
* Maneja la navegación con teclas en menús desplegables y componentes interactivos
|
||||
*/
|
||||
function setupKeyboardNavigation() {
|
||||
// Navegación en menús desplegables de Bootstrap
|
||||
setupBootstrapDropdownKeyboard();
|
||||
|
||||
// Navegación en menús personalizados
|
||||
setupCustomMenuKeyboard();
|
||||
|
||||
// Escapar de modales con ESC
|
||||
setupModalEscape();
|
||||
}
|
||||
|
||||
/**
|
||||
* Navegación por teclado en dropdowns de Bootstrap
|
||||
*/
|
||||
function setupBootstrapDropdownKeyboard() {
|
||||
const dropdownToggles = document.querySelectorAll('[data-bs-toggle="dropdown"]');
|
||||
|
||||
dropdownToggles.forEach(function(toggle) {
|
||||
const dropdown = toggle.nextElementSibling;
|
||||
|
||||
if (!dropdown || !dropdown.classList.contains('dropdown-menu')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Abrir dropdown con Enter o Space
|
||||
toggle.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggle.click();
|
||||
|
||||
// Focus en el primer item del menú
|
||||
setTimeout(function() {
|
||||
const firstItem = dropdown.querySelector('a, button');
|
||||
if (firstItem) {
|
||||
firstItem.focus();
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// Flecha abajo para abrir y enfocar primer item
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (!dropdown.classList.contains('show')) {
|
||||
toggle.click();
|
||||
}
|
||||
setTimeout(function() {
|
||||
const firstItem = dropdown.querySelector('a, button');
|
||||
if (firstItem) {
|
||||
firstItem.focus();
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
// Navegación dentro del dropdown con flechas
|
||||
dropdown.addEventListener('keydown', function(e) {
|
||||
const items = Array.from(dropdown.querySelectorAll('a, button'));
|
||||
const currentIndex = items.indexOf(document.activeElement);
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
const nextIndex = (currentIndex + 1) % items.length;
|
||||
items[nextIndex].focus();
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
const prevIndex = currentIndex - 1 < 0 ? items.length - 1 : currentIndex - 1;
|
||||
items[prevIndex].focus();
|
||||
}
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
toggle.click(); // Cerrar dropdown
|
||||
toggle.focus(); // Devolver focus al toggle
|
||||
}
|
||||
|
||||
if (e.key === 'Tab') {
|
||||
// Permitir tab normal pero cerrar dropdown
|
||||
toggle.click();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Navegación por teclado en menús personalizados (WordPress)
|
||||
*/
|
||||
function setupCustomMenuKeyboard() {
|
||||
const menuItems = document.querySelectorAll('.menu-item-has-children > a');
|
||||
|
||||
menuItems.forEach(function(link) {
|
||||
const parentItem = link.parentElement;
|
||||
const submenu = parentItem.querySelector('.sub-menu');
|
||||
|
||||
if (!submenu) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Inicializar ARIA attributes
|
||||
link.setAttribute('aria-haspopup', 'true');
|
||||
link.setAttribute('aria-expanded', 'false');
|
||||
submenu.setAttribute('aria-hidden', 'true');
|
||||
|
||||
// Toggle submenu con Enter o Space
|
||||
link.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleSubmenu(parentItem, submenu, link);
|
||||
}
|
||||
|
||||
// Flecha derecha para abrir submenu
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
openSubmenu(parentItem, submenu, link);
|
||||
|
||||
// Focus en primer item del submenu
|
||||
const firstItem = submenu.querySelector('a');
|
||||
if (firstItem) {
|
||||
firstItem.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Escape para cerrar submenu
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
closeSubmenu(parentItem, submenu, link);
|
||||
link.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Navegación dentro del submenu
|
||||
const submenuItems = submenu.querySelectorAll('a');
|
||||
submenuItems.forEach(function(item, index) {
|
||||
item.addEventListener('keydown', function(e) {
|
||||
// Flecha arriba/abajo para navegar entre items
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
const nextItem = submenuItems[index + 1];
|
||||
if (nextItem) {
|
||||
nextItem.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (index === 0) {
|
||||
link.focus();
|
||||
} else {
|
||||
submenuItems[index - 1].focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Flecha izquierda para volver al menú padre
|
||||
if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
closeSubmenu(parentItem, submenu, link);
|
||||
link.focus();
|
||||
}
|
||||
|
||||
// Escape para cerrar submenu
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
closeSubmenu(parentItem, submenu, link);
|
||||
link.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Cerrar submenu cuando focus sale del elemento
|
||||
parentItem.addEventListener('focusout', function(e) {
|
||||
// Verificar si el nuevo focus está fuera del menú
|
||||
setTimeout(function() {
|
||||
if (!parentItem.contains(document.activeElement)) {
|
||||
closeSubmenu(parentItem, submenu, link);
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle submenu (abrir/cerrar)
|
||||
*/
|
||||
function toggleSubmenu(parentItem, submenu, link) {
|
||||
const isOpen = parentItem.classList.contains('submenu-open');
|
||||
|
||||
if (isOpen) {
|
||||
closeSubmenu(parentItem, submenu, link);
|
||||
} else {
|
||||
openSubmenu(parentItem, submenu, link);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Abrir submenu
|
||||
*/
|
||||
function openSubmenu(parentItem, submenu, link) {
|
||||
parentItem.classList.add('submenu-open');
|
||||
link.setAttribute('aria-expanded', 'true');
|
||||
submenu.setAttribute('aria-hidden', 'false');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cerrar submenu
|
||||
*/
|
||||
function closeSubmenu(parentItem, submenu, link) {
|
||||
parentItem.classList.remove('submenu-open');
|
||||
link.setAttribute('aria-expanded', 'false');
|
||||
submenu.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cerrar modales con tecla Escape
|
||||
*/
|
||||
function setupModalEscape() {
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') {
|
||||
// Bootstrap modals
|
||||
const openModals = document.querySelectorAll('.modal.show');
|
||||
openModals.forEach(function(modal) {
|
||||
const bsModal = bootstrap.Modal.getInstance(modal);
|
||||
if (bsModal) {
|
||||
bsModal.hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Offcanvas
|
||||
const openOffcanvas = document.querySelectorAll('.offcanvas.show');
|
||||
openOffcanvas.forEach(function(offcanvas) {
|
||||
const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvas);
|
||||
if (bsOffcanvas) {
|
||||
bsOffcanvas.hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestión de Focus
|
||||
* Maneja el focus visible y trap de focus en modales
|
||||
*/
|
||||
function setupFocusManagement() {
|
||||
// Mostrar outline solo con navegación por teclado
|
||||
setupFocusVisible();
|
||||
|
||||
// Trap focus en modales
|
||||
setupModalFocusTrap();
|
||||
|
||||
// Restaurar focus al cerrar modales
|
||||
setupFocusRestore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus visible solo con teclado (no con mouse)
|
||||
*/
|
||||
function setupFocusVisible() {
|
||||
let usingMouse = false;
|
||||
|
||||
document.addEventListener('mousedown', function() {
|
||||
usingMouse = true;
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Tab') {
|
||||
usingMouse = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Agregar clase al body para indicar método de navegación
|
||||
document.addEventListener('focusin', function() {
|
||||
if (usingMouse) {
|
||||
document.body.classList.add('using-mouse');
|
||||
} else {
|
||||
document.body.classList.remove('using-mouse');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Trap focus dentro de modales (evitar que Tab salga del modal)
|
||||
*/
|
||||
function setupModalFocusTrap() {
|
||||
const modals = document.querySelectorAll('.modal, [role="dialog"]');
|
||||
|
||||
modals.forEach(function(modal) {
|
||||
modal.addEventListener('keydown', function(e) {
|
||||
if (e.key !== 'Tab') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Solo aplicar trap si el modal está visible
|
||||
if (!modal.classList.contains('show') && modal.style.display !== 'block') {
|
||||
return;
|
||||
}
|
||||
|
||||
const focusableElements = modal.querySelectorAll(
|
||||
'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
|
||||
if (focusableElements.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
|
||||
if (e.shiftKey) {
|
||||
// Shift + Tab - navegar hacia atrás
|
||||
if (document.activeElement === firstElement) {
|
||||
e.preventDefault();
|
||||
lastElement.focus();
|
||||
}
|
||||
} else {
|
||||
// Tab - navegar hacia adelante
|
||||
if (document.activeElement === lastElement) {
|
||||
e.preventDefault();
|
||||
firstElement.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Restaurar focus al elemento que abrió el modal
|
||||
*/
|
||||
function setupFocusRestore() {
|
||||
let lastFocusedElement = null;
|
||||
|
||||
// Guardar elemento con focus antes de abrir modal
|
||||
document.addEventListener('show.bs.modal', function(e) {
|
||||
lastFocusedElement = document.activeElement;
|
||||
});
|
||||
|
||||
document.addEventListener('show.bs.offcanvas', function(e) {
|
||||
lastFocusedElement = document.activeElement;
|
||||
});
|
||||
|
||||
// Restaurar focus al cerrar modal
|
||||
document.addEventListener('hidden.bs.modal', function(e) {
|
||||
if (lastFocusedElement) {
|
||||
lastFocusedElement.focus();
|
||||
lastFocusedElement = null;
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('hidden.bs.offcanvas', function(e) {
|
||||
if (lastFocusedElement) {
|
||||
lastFocusedElement.focus();
|
||||
lastFocusedElement = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* ARIA Live Regions
|
||||
* Crear regiones live para anuncios dinámicos a lectores de pantalla
|
||||
*/
|
||||
function setupAriaLiveRegions() {
|
||||
// Crear región live polite si no existe
|
||||
if (!document.getElementById('aria-live-polite')) {
|
||||
const liveRegion = document.createElement('div');
|
||||
liveRegion.id = 'aria-live-polite';
|
||||
liveRegion.setAttribute('aria-live', 'polite');
|
||||
liveRegion.setAttribute('aria-atomic', 'true');
|
||||
liveRegion.className = 'sr-only';
|
||||
document.body.appendChild(liveRegion);
|
||||
}
|
||||
|
||||
// Crear región live assertive si no existe
|
||||
if (!document.getElementById('aria-live-assertive')) {
|
||||
const liveRegion = document.createElement('div');
|
||||
liveRegion.id = 'aria-live-assertive';
|
||||
liveRegion.setAttribute('aria-live', 'assertive');
|
||||
liveRegion.setAttribute('aria-atomic', 'true');
|
||||
liveRegion.className = 'sr-only';
|
||||
document.body.appendChild(liveRegion);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Anunciar cambios de página a lectores de pantalla
|
||||
*/
|
||||
function announcePageChanges() {
|
||||
// Anunciar cambios de ruta en navegación (para SPAs o AJAX)
|
||||
let currentPath = window.location.pathname;
|
||||
|
||||
// Observer para cambios en el título de la página
|
||||
const titleObserver = new MutationObserver(function(mutations) {
|
||||
mutations.forEach(function(mutation) {
|
||||
if (mutation.type === 'childList') {
|
||||
const newTitle = document.title;
|
||||
announce('Página cargada: ' + newTitle, 'polite');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const titleElement = document.querySelector('title');
|
||||
if (titleElement) {
|
||||
titleObserver.observe(titleElement, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
}
|
||||
|
||||
// Detectar navegación por history API
|
||||
const originalPushState = history.pushState;
|
||||
history.pushState = function() {
|
||||
originalPushState.apply(history, arguments);
|
||||
|
||||
if (window.location.pathname !== currentPath) {
|
||||
currentPath = window.location.pathname;
|
||||
setTimeout(function() {
|
||||
announce('Página cargada: ' + document.title, 'polite');
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Función helper para anunciar mensajes a lectores de pantalla
|
||||
*
|
||||
* @param {string} message - Mensaje a anunciar
|
||||
* @param {string} priority - 'polite' o 'assertive'
|
||||
*/
|
||||
window.announceToScreenReader = function(message, priority) {
|
||||
announce(message, priority);
|
||||
};
|
||||
|
||||
function announce(message, priority) {
|
||||
priority = priority || 'polite';
|
||||
const liveRegionId = 'aria-live-' + priority;
|
||||
const liveRegion = document.getElementById(liveRegionId);
|
||||
|
||||
if (!liveRegion) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Limpiar y agregar mensaje
|
||||
liveRegion.textContent = '';
|
||||
setTimeout(function() {
|
||||
liveRegion.textContent = message;
|
||||
}, 100);
|
||||
|
||||
// Limpiar después de 5 segundos
|
||||
setTimeout(function() {
|
||||
liveRegion.textContent = '';
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Manejar clicks en elementos con data-announce
|
||||
* Permite anunciar acciones a lectores de pantalla
|
||||
*/
|
||||
function setupDataAnnounce() {
|
||||
document.addEventListener('click', function(e) {
|
||||
const target = e.target.closest('[data-announce]');
|
||||
if (target) {
|
||||
const message = target.getAttribute('data-announce');
|
||||
const priority = target.getAttribute('data-announce-priority') || 'polite';
|
||||
announce(message, priority);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicializar cuando DOM está listo
|
||||
*/
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
init();
|
||||
setupDataAnnounce();
|
||||
});
|
||||
} else {
|
||||
init();
|
||||
setupDataAnnounce();
|
||||
}
|
||||
|
||||
})();
|
||||
216
Assets/Js/adsense-loader.js
Normal file
216
Assets/Js/adsense-loader.js
Normal file
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Cargador Retrasado de AdSense
|
||||
*
|
||||
* Este script retrasa la carga de Google AdSense hasta que haya interacción
|
||||
* del usuario o se cumpla un timeout, mejorando el rendimiento de carga inicial.
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// Configuración
|
||||
const CONFIG = {
|
||||
timeout: 5000, // Timeout de fallback en milisegundos
|
||||
loadedClass: 'adsense-loaded',
|
||||
debug: false // Cambiar a true para logs en consola
|
||||
};
|
||||
|
||||
// Estado
|
||||
let adsenseLoaded = false;
|
||||
let loadTimeout = null;
|
||||
|
||||
/**
|
||||
* Registra mensajes de debug si el modo debug está habilitado
|
||||
* @param {string} message - El mensaje a registrar
|
||||
*/
|
||||
function debugLog(message) {
|
||||
if (CONFIG.debug && typeof console !== 'undefined') {
|
||||
console.log('[AdSense Loader] ' + message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Carga los scripts de AdSense e inicializa los ads
|
||||
*/
|
||||
function loadAdSense() {
|
||||
// Prevenir múltiples cargas
|
||||
if (adsenseLoaded) {
|
||||
debugLog('AdSense ya fue cargado, omitiendo...');
|
||||
return;
|
||||
}
|
||||
|
||||
adsenseLoaded = true;
|
||||
debugLog('Cargando scripts de AdSense...');
|
||||
|
||||
// Limpiar el timeout si existe
|
||||
if (loadTimeout) {
|
||||
clearTimeout(loadTimeout);
|
||||
loadTimeout = null;
|
||||
}
|
||||
|
||||
// Remover event listeners para prevenir múltiples triggers
|
||||
removeEventListeners();
|
||||
|
||||
// Cargar etiquetas de script de AdSense
|
||||
loadAdSenseScripts();
|
||||
|
||||
// Ejecutar scripts de push de AdSense
|
||||
executeAdSensePushScripts();
|
||||
|
||||
// Agregar clase loaded al body
|
||||
document.body.classList.add(CONFIG.loadedClass);
|
||||
|
||||
debugLog('Carga de AdSense completada');
|
||||
}
|
||||
|
||||
/**
|
||||
* Encuentra y carga todas las etiquetas de script de AdSense retrasadas
|
||||
*/
|
||||
function loadAdSenseScripts() {
|
||||
const delayedScripts = document.querySelectorAll('script[data-adsense-script]');
|
||||
|
||||
if (delayedScripts.length === 0) {
|
||||
debugLog('No se encontraron scripts retrasados de AdSense');
|
||||
return;
|
||||
}
|
||||
|
||||
debugLog('Se encontraron ' + delayedScripts.length + ' script(s) retrasado(s) de AdSense');
|
||||
|
||||
delayedScripts.forEach(function(oldScript) {
|
||||
const newScript = document.createElement('script');
|
||||
|
||||
// Copiar atributos
|
||||
if (oldScript.src) {
|
||||
newScript.src = oldScript.src;
|
||||
}
|
||||
|
||||
// Establecer atributo async
|
||||
newScript.async = true;
|
||||
|
||||
// Copiar crossorigin si está presente
|
||||
if (oldScript.getAttribute('crossorigin')) {
|
||||
newScript.crossorigin = oldScript.getAttribute('crossorigin');
|
||||
}
|
||||
|
||||
// Reemplazar script viejo con el nuevo
|
||||
oldScript.parentNode.replaceChild(newScript, oldScript);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ejecuta scripts de push de AdSense retrasados
|
||||
*/
|
||||
function executeAdSensePushScripts() {
|
||||
const delayedPushScripts = document.querySelectorAll('script[data-adsense-push]');
|
||||
|
||||
if (delayedPushScripts.length === 0) {
|
||||
debugLog('No se encontraron scripts de push retrasados de AdSense');
|
||||
return;
|
||||
}
|
||||
|
||||
debugLog('Se encontraron ' + delayedPushScripts.length + ' script(s) de push retrasado(s)');
|
||||
|
||||
// Inicializar array adsbygoogle si no existe
|
||||
window.adsbygoogle = window.adsbygoogle || [];
|
||||
|
||||
delayedPushScripts.forEach(function(oldScript) {
|
||||
const scriptContent = oldScript.innerHTML;
|
||||
|
||||
// Crear y ejecutar nuevo script
|
||||
const newScript = document.createElement('script');
|
||||
newScript.innerHTML = scriptContent;
|
||||
newScript.type = 'text/javascript';
|
||||
|
||||
// Reemplazar script viejo con el nuevo
|
||||
oldScript.parentNode.replaceChild(newScript, oldScript);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Manejador de eventos para interacciones del usuario
|
||||
*/
|
||||
function handleUserInteraction() {
|
||||
debugLog('Interacción del usuario detectada');
|
||||
loadAdSense();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remueve todos los event listeners
|
||||
*/
|
||||
function removeEventListeners() {
|
||||
window.removeEventListener('scroll', handleUserInteraction, { passive: true });
|
||||
window.removeEventListener('mousemove', handleUserInteraction, { passive: true });
|
||||
window.removeEventListener('touchstart', handleUserInteraction, { passive: true });
|
||||
window.removeEventListener('click', handleUserInteraction, { passive: true });
|
||||
window.removeEventListener('keydown', handleUserInteraction, { passive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Agrega event listeners para interacciones del usuario
|
||||
*/
|
||||
function addEventListeners() {
|
||||
debugLog('Agregando event listeners para interacción del usuario');
|
||||
|
||||
// Evento de scroll - cargar en primer scroll
|
||||
window.addEventListener('scroll', handleUserInteraction, { passive: true, once: true });
|
||||
|
||||
// Movimiento de mouse - cargar cuando el usuario mueve el mouse
|
||||
window.addEventListener('mousemove', handleUserInteraction, { passive: true, once: true });
|
||||
|
||||
// Eventos táctiles - cargar en primer toque (móviles)
|
||||
window.addEventListener('touchstart', handleUserInteraction, { passive: true, once: true });
|
||||
|
||||
// Eventos de click - cargar en primer click
|
||||
window.addEventListener('click', handleUserInteraction, { passive: true, once: true });
|
||||
|
||||
// Eventos de teclado - cargar en primera pulsación de tecla
|
||||
window.addEventListener('keydown', handleUserInteraction, { passive: true, once: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Establece timeout de fallback para cargar AdSense después del tiempo especificado
|
||||
*/
|
||||
function setTimeoutFallback() {
|
||||
debugLog('Estableciendo timeout de fallback (' + CONFIG.timeout + 'ms)');
|
||||
|
||||
loadTimeout = setTimeout(function() {
|
||||
debugLog('Timeout alcanzado, cargando AdSense');
|
||||
loadAdSense();
|
||||
}, CONFIG.timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicializa el cargador retrasado de AdSense
|
||||
*/
|
||||
function init() {
|
||||
// Verificar si el retardo de AdSense está habilitado
|
||||
if (!window.roiAdsenseDelayed) {
|
||||
debugLog('Retardo de AdSense no habilitado');
|
||||
return;
|
||||
}
|
||||
|
||||
debugLog('Inicializando cargador retrasado de AdSense');
|
||||
|
||||
// Verificar si la página ya está interactiva o completa
|
||||
if (document.readyState === 'interactive' || document.readyState === 'complete') {
|
||||
debugLog('Página ya cargada, iniciando listeners');
|
||||
addEventListeners();
|
||||
setTimeoutFallback();
|
||||
} else {
|
||||
// Esperar a que el DOM esté listo
|
||||
debugLog('Esperando a DOMContentLoaded');
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
debugLog('DOMContentLoaded disparado');
|
||||
addEventListeners();
|
||||
setTimeoutFallback();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Iniciar inicialización
|
||||
init();
|
||||
|
||||
})();
|
||||
99
Assets/Js/apu-tables-auto-class.js
Normal file
99
Assets/Js/apu-tables-auto-class.js
Normal file
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Auto-detectar y agregar clases a filas especiales de tablas APU
|
||||
*
|
||||
* Este script detecta automáticamente filas especiales en tablas .desglose y .analisis
|
||||
* y les agrega las clases CSS correspondientes para que se apliquen los estilos correctos.
|
||||
*
|
||||
* Detecta:
|
||||
* - Section headers: Material, Mano de Obra, Herramienta, Equipo
|
||||
* - Subtotal rows: Filas que empiezan con "Suma de"
|
||||
* - Total row: Costo Directo
|
||||
*
|
||||
* @package Apus_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Agrega clases a filas especiales de tablas APU
|
||||
*/
|
||||
function applyApuTableClasses() {
|
||||
// Buscar todas las tablas con clase .desglose o .analisis
|
||||
const tables = document.querySelectorAll('.desglose table, .analisis table');
|
||||
|
||||
if (tables.length === 0) {
|
||||
return; // No hay tablas APU en esta página
|
||||
}
|
||||
|
||||
let classesAdded = 0;
|
||||
|
||||
tables.forEach(function(table) {
|
||||
const rows = table.querySelectorAll('tbody tr');
|
||||
|
||||
rows.forEach(function(row) {
|
||||
// Evitar procesar filas que ya tienen clase
|
||||
if (row.classList.contains('section-header') ||
|
||||
row.classList.contains('subtotal-row') ||
|
||||
row.classList.contains('total-row')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const secondCell = row.querySelector('td:nth-child(2)');
|
||||
if (!secondCell) {
|
||||
return; // Fila sin segunda celda
|
||||
}
|
||||
|
||||
const text = secondCell.textContent.trim();
|
||||
|
||||
// Detectar section headers
|
||||
if (text === 'Material' ||
|
||||
text === 'Mano de Obra' ||
|
||||
text === 'Herramienta' ||
|
||||
text === 'Equipo' ||
|
||||
text === 'MATERIAL' ||
|
||||
text === 'MANO DE OBRA' ||
|
||||
text === 'HERRAMIENTA' ||
|
||||
text === 'EQUIPO') {
|
||||
row.classList.add('section-header');
|
||||
classesAdded++;
|
||||
return;
|
||||
}
|
||||
|
||||
// Detectar subtotales (cualquier variación de "Suma de")
|
||||
if (text.toLowerCase().startsWith('suma de ') ||
|
||||
text.toLowerCase().startsWith('subtotal ')) {
|
||||
row.classList.add('subtotal-row');
|
||||
classesAdded++;
|
||||
return;
|
||||
}
|
||||
|
||||
// Detectar total final
|
||||
if (text === 'Costo Directo' ||
|
||||
text === 'COSTO DIRECTO' ||
|
||||
text === 'Total' ||
|
||||
text === 'TOTAL' ||
|
||||
text === 'Costo directo') {
|
||||
row.classList.add('total-row');
|
||||
classesAdded++;
|
||||
return;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Log para debugging (solo en desarrollo)
|
||||
if (classesAdded > 0 && window.console) {
|
||||
console.log('[APU Tables] Clases agregadas automáticamente: ' + classesAdded);
|
||||
}
|
||||
}
|
||||
|
||||
// Ejecutar cuando el DOM esté listo
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', applyApuTableClasses);
|
||||
} else {
|
||||
// DOM ya está listo
|
||||
applyApuTableClasses();
|
||||
}
|
||||
|
||||
})();
|
||||
7
Assets/Js/bootstrap.bundle.min.js
vendored
Normal file
7
Assets/Js/bootstrap.bundle.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
343
Assets/Js/footer-contact.js
Normal file
343
Assets/Js/footer-contact.js
Normal file
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* Footer Contact Form Handler (Issue #37)
|
||||
*
|
||||
* Maneja la validación, envío y tracking del formulario de contacto del footer.
|
||||
* Incluye:
|
||||
* - Validaciones de email y WhatsApp
|
||||
* - Envío a webhook
|
||||
* - Google Analytics 4 tracking
|
||||
* - Estados de loading y mensajes de feedback
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// Configuración del webhook
|
||||
const WEBHOOK_URL = 'https://hook.us2.make.com/iq8p4q9w50a12crlb58d4h1o6lwu4f47';
|
||||
const FORM_SOURCE = 'ROI Website - Footer Contact Form';
|
||||
|
||||
// Expresiones regulares para validación
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
const WHATSAPP_REGEX = /^\+?[\d\s-]{10,15}$/;
|
||||
|
||||
/**
|
||||
* Inicializar el formulario cuando el DOM está listo
|
||||
*/
|
||||
function init() {
|
||||
const form = document.getElementById('footerContactForm');
|
||||
if (!form) return;
|
||||
|
||||
// Agregar event listeners
|
||||
form.addEventListener('submit', handleSubmit);
|
||||
|
||||
// Validación en tiempo real para campos específicos
|
||||
const emailInput = document.getElementById('footerEmail');
|
||||
const whatsappInput = document.getElementById('footerWhatsapp');
|
||||
|
||||
if (emailInput) {
|
||||
emailInput.addEventListener('blur', function() {
|
||||
validateEmail(this);
|
||||
});
|
||||
emailInput.addEventListener('input', function() {
|
||||
if (this.classList.contains('is-invalid')) {
|
||||
validateEmail(this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (whatsappInput) {
|
||||
whatsappInput.addEventListener('blur', function() {
|
||||
validateWhatsApp(this);
|
||||
});
|
||||
whatsappInput.addEventListener('input', function() {
|
||||
if (this.classList.contains('is-invalid')) {
|
||||
validateWhatsApp(this);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validar email
|
||||
* @param {HTMLInputElement} input - Campo de input
|
||||
* @returns {boolean} - True si es válido
|
||||
*/
|
||||
function validateEmail(input) {
|
||||
const value = input.value.trim();
|
||||
const isValid = EMAIL_REGEX.test(value);
|
||||
|
||||
if (value === '') {
|
||||
input.classList.remove('is-valid', 'is-invalid');
|
||||
return true; // Si está vacío pero no es requerido, es válido
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
input.classList.remove('is-invalid');
|
||||
input.classList.add('is-valid');
|
||||
} else {
|
||||
input.classList.remove('is-valid');
|
||||
input.classList.add('is-invalid');
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validar WhatsApp (10-15 dígitos)
|
||||
* @param {HTMLInputElement} input - Campo de input
|
||||
* @returns {boolean} - True si es válido
|
||||
*/
|
||||
function validateWhatsApp(input) {
|
||||
const value = input.value.trim();
|
||||
// Remover espacios, guiones y signos + para contar solo dígitos
|
||||
const digitsOnly = value.replace(/[\s\-+]/g, '');
|
||||
const isValid = WHATSAPP_REGEX.test(value) && digitsOnly.length >= 10 && digitsOnly.length <= 15;
|
||||
|
||||
if (value === '') {
|
||||
input.classList.remove('is-valid', 'is-invalid');
|
||||
return false; // WhatsApp es requerido
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
input.classList.remove('is-invalid');
|
||||
input.classList.add('is-valid');
|
||||
} else {
|
||||
input.classList.remove('is-valid');
|
||||
input.classList.add('is-invalid');
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validar todos los campos del formulario
|
||||
* @param {HTMLFormElement} form - Formulario
|
||||
* @returns {boolean} - True si todo es válido
|
||||
*/
|
||||
function validateForm(form) {
|
||||
let isValid = true;
|
||||
|
||||
// Validar campos requeridos
|
||||
const fullName = form.querySelector('#footerFullName');
|
||||
const email = form.querySelector('#footerEmail');
|
||||
const whatsapp = form.querySelector('#footerWhatsapp');
|
||||
|
||||
if (fullName && fullName.value.trim() === '') {
|
||||
fullName.classList.add('is-invalid');
|
||||
isValid = false;
|
||||
} else if (fullName) {
|
||||
fullName.classList.remove('is-invalid');
|
||||
fullName.classList.add('is-valid');
|
||||
}
|
||||
|
||||
if (email && !validateEmail(email)) {
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (whatsapp && !validateWhatsApp(whatsapp)) {
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mostrar mensaje de feedback
|
||||
* @param {string} message - Mensaje a mostrar
|
||||
* @param {string} type - Tipo: 'success', 'danger', 'info'
|
||||
*/
|
||||
function showMessage(message, type) {
|
||||
const messageDiv = document.getElementById('footerFormMessage');
|
||||
if (!messageDiv) return;
|
||||
|
||||
messageDiv.className = 'col-12 mt-2 alert alert-' + type;
|
||||
messageDiv.textContent = message;
|
||||
messageDiv.style.display = 'block';
|
||||
messageDiv.classList.add('show');
|
||||
|
||||
// Scroll suave al mensaje
|
||||
messageDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
|
||||
// Auto-ocultar mensajes de éxito después de 5 segundos
|
||||
if (type === 'success') {
|
||||
setTimeout(function() {
|
||||
hideMessage();
|
||||
}, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ocultar mensaje
|
||||
*/
|
||||
function hideMessage() {
|
||||
const messageDiv = document.getElementById('footerFormMessage');
|
||||
if (!messageDiv) return;
|
||||
|
||||
messageDiv.classList.remove('show');
|
||||
setTimeout(function() {
|
||||
messageDiv.style.display = 'none';
|
||||
}, 150);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trackear evento en Google Analytics 4
|
||||
* @param {string} eventName - Nombre del evento
|
||||
* @param {Object} params - Parámetros adicionales
|
||||
*/
|
||||
function trackGA4Event(eventName, params) {
|
||||
if (typeof gtag === 'function') {
|
||||
gtag('event', eventName, params);
|
||||
} else if (typeof dataLayer !== 'undefined') {
|
||||
dataLayer.push({
|
||||
'event': eventName,
|
||||
...params
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preparar datos del formulario
|
||||
* @param {HTMLFormElement} form - Formulario
|
||||
* @returns {Object} - Datos del formulario
|
||||
*/
|
||||
function getFormData(form) {
|
||||
return {
|
||||
fullName: form.querySelector('#footerFullName').value.trim(),
|
||||
company: form.querySelector('#footerCompany').value.trim() || 'N/A',
|
||||
whatsapp: form.querySelector('#footerWhatsapp').value.trim(),
|
||||
email: form.querySelector('#footerEmail').value.trim(),
|
||||
comments: form.querySelector('#footerComments').value.trim() || 'Sin comentarios',
|
||||
source: FORM_SOURCE,
|
||||
timestamp: new Date().toISOString(),
|
||||
pageUrl: window.location.href,
|
||||
pageTitle: document.title
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enviar datos al webhook
|
||||
* @param {Object} data - Datos a enviar
|
||||
* @returns {Promise} - Promesa de fetch
|
||||
*/
|
||||
async function sendToWebhook(data) {
|
||||
const response = await fetch(WEBHOOK_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Error en el servidor: ' + response.status);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resetear el formulario
|
||||
* @param {HTMLFormElement} form - Formulario
|
||||
*/
|
||||
function resetForm(form) {
|
||||
form.reset();
|
||||
|
||||
// Remover todas las clases de validación
|
||||
const inputs = form.querySelectorAll('.form-control');
|
||||
inputs.forEach(function(input) {
|
||||
input.classList.remove('is-valid', 'is-invalid');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Manejar el envío del formulario
|
||||
* @param {Event} e - Evento de submit
|
||||
*/
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const form = e.target;
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
|
||||
// Ocultar mensaje anterior
|
||||
hideMessage();
|
||||
|
||||
// Validar formulario
|
||||
if (!validateForm(form)) {
|
||||
showMessage('Por favor, completa todos los campos requeridos correctamente.', 'danger');
|
||||
|
||||
// Track error de validación
|
||||
trackGA4Event('form_validation_error', {
|
||||
form_name: 'footer_contact',
|
||||
form_source: FORM_SOURCE
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Deshabilitar botón y mostrar loading
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.classList.add('loading');
|
||||
const originalText = submitBtn.innerHTML;
|
||||
|
||||
// Track inicio de envío
|
||||
trackGA4Event('form_submit_start', {
|
||||
form_name: 'footer_contact',
|
||||
form_source: FORM_SOURCE
|
||||
});
|
||||
|
||||
try {
|
||||
// Preparar y enviar datos
|
||||
const formData = getFormData(form);
|
||||
await sendToWebhook(formData);
|
||||
|
||||
// Éxito
|
||||
showMessage('¡Gracias por tu mensaje! Nos pondremos en contacto contigo pronto.', 'success');
|
||||
resetForm(form);
|
||||
|
||||
// Track éxito
|
||||
trackGA4Event('form_submit_success', {
|
||||
form_name: 'footer_contact',
|
||||
form_source: FORM_SOURCE,
|
||||
has_company: formData.company !== 'N/A',
|
||||
has_comments: formData.comments !== 'Sin comentarios'
|
||||
});
|
||||
|
||||
// Track conversión
|
||||
trackGA4Event('generate_lead', {
|
||||
currency: 'MXN',
|
||||
value: 1,
|
||||
form_name: 'footer_contact',
|
||||
form_source: FORM_SOURCE
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error al enviar el formulario:', error);
|
||||
showMessage('Hubo un error al enviar tu mensaje. Por favor, intenta nuevamente.', 'danger');
|
||||
|
||||
// Track error
|
||||
trackGA4Event('form_submit_error', {
|
||||
form_name: 'footer_contact',
|
||||
form_source: FORM_SOURCE,
|
||||
error_message: error.message
|
||||
});
|
||||
|
||||
} finally {
|
||||
// Restaurar botón
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.classList.remove('loading');
|
||||
submitBtn.innerHTML = originalText;
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializar cuando el DOM esté listo
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
})();
|
||||
342
Assets/Js/header.js
Normal file
342
Assets/Js/header.js
Normal file
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Header Navigation JavaScript
|
||||
*
|
||||
* This file handles:
|
||||
* - Mobile hamburger menu toggle
|
||||
* - Sticky header behavior
|
||||
* - Smooth scroll to anchors (optional)
|
||||
* - Accessibility features (keyboard navigation, ARIA attributes)
|
||||
* - Body scroll locking when mobile menu is open
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Initialize on DOM ready
|
||||
*/
|
||||
function init() {
|
||||
setupMobileMenu();
|
||||
setupStickyHeader();
|
||||
setupSmoothScroll();
|
||||
setupKeyboardNavigation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile Menu Functionality
|
||||
*/
|
||||
function setupMobileMenu() {
|
||||
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
|
||||
const mobileMenu = document.getElementById('mobile-menu');
|
||||
const mobileMenuOverlay = document.getElementById('mobile-menu-overlay');
|
||||
const mobileMenuClose = document.getElementById('mobile-menu-close');
|
||||
|
||||
if (!mobileMenuToggle || !mobileMenu || !mobileMenuOverlay) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Open mobile menu
|
||||
mobileMenuToggle.addEventListener('click', function() {
|
||||
openMobileMenu();
|
||||
});
|
||||
|
||||
// Close mobile menu via close button
|
||||
if (mobileMenuClose) {
|
||||
mobileMenuClose.addEventListener('click', function() {
|
||||
closeMobileMenu();
|
||||
});
|
||||
}
|
||||
|
||||
// Close mobile menu via overlay click
|
||||
mobileMenuOverlay.addEventListener('click', function() {
|
||||
closeMobileMenu();
|
||||
});
|
||||
|
||||
// Close mobile menu on Escape key
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape' && mobileMenu.classList.contains('active')) {
|
||||
closeMobileMenu();
|
||||
mobileMenuToggle.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Close mobile menu when clicking a menu link
|
||||
const mobileMenuLinks = mobileMenu.querySelectorAll('a');
|
||||
mobileMenuLinks.forEach(function(link) {
|
||||
link.addEventListener('click', function() {
|
||||
closeMobileMenu();
|
||||
});
|
||||
});
|
||||
|
||||
// Handle window resize - close mobile menu if switching to desktop
|
||||
let resizeTimer;
|
||||
window.addEventListener('resize', function() {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(function() {
|
||||
if (window.innerWidth >= 768 && mobileMenu.classList.contains('active')) {
|
||||
closeMobileMenu();
|
||||
}
|
||||
}, 250);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open mobile menu
|
||||
*/
|
||||
function openMobileMenu() {
|
||||
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
|
||||
const mobileMenu = document.getElementById('mobile-menu');
|
||||
const mobileMenuOverlay = document.getElementById('mobile-menu-overlay');
|
||||
|
||||
// Add active classes
|
||||
mobileMenu.classList.add('active');
|
||||
mobileMenuOverlay.classList.add('active');
|
||||
document.body.classList.add('mobile-menu-open');
|
||||
|
||||
// Update ARIA attributes
|
||||
mobileMenuToggle.setAttribute('aria-expanded', 'true');
|
||||
mobileMenu.setAttribute('aria-hidden', 'false');
|
||||
mobileMenuOverlay.setAttribute('aria-hidden', 'false');
|
||||
|
||||
// Focus trap - focus first menu item
|
||||
const firstMenuItem = mobileMenu.querySelector('a');
|
||||
if (firstMenuItem) {
|
||||
setTimeout(function() {
|
||||
firstMenuItem.focus();
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close mobile menu
|
||||
*/
|
||||
function closeMobileMenu() {
|
||||
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
|
||||
const mobileMenu = document.getElementById('mobile-menu');
|
||||
const mobileMenuOverlay = document.getElementById('mobile-menu-overlay');
|
||||
|
||||
// Remove active classes
|
||||
mobileMenu.classList.remove('active');
|
||||
mobileMenuOverlay.classList.remove('active');
|
||||
document.body.classList.remove('mobile-menu-open');
|
||||
|
||||
// Update ARIA attributes
|
||||
mobileMenuToggle.setAttribute('aria-expanded', 'false');
|
||||
mobileMenu.setAttribute('aria-hidden', 'true');
|
||||
mobileMenuOverlay.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sticky Header Behavior
|
||||
*/
|
||||
function setupStickyHeader() {
|
||||
const header = document.getElementById('masthead');
|
||||
|
||||
if (!header) {
|
||||
return;
|
||||
}
|
||||
|
||||
let lastScrollTop = 0;
|
||||
let scrollThreshold = 100;
|
||||
|
||||
window.addEventListener('scroll', function() {
|
||||
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
|
||||
|
||||
// Add/remove scrolled class based on scroll position
|
||||
if (scrollTop > scrollThreshold) {
|
||||
header.classList.add('scrolled');
|
||||
} else {
|
||||
header.classList.remove('scrolled');
|
||||
}
|
||||
|
||||
lastScrollTop = scrollTop;
|
||||
}, { passive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Smooth Scroll to Anchors (Optional)
|
||||
*/
|
||||
function setupSmoothScroll() {
|
||||
// Check if user prefers reduced motion
|
||||
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
if (prefersReducedMotion) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all anchor links
|
||||
const anchorLinks = document.querySelectorAll('a[href^="#"]');
|
||||
|
||||
anchorLinks.forEach(function(link) {
|
||||
link.addEventListener('click', function(e) {
|
||||
const href = this.getAttribute('href');
|
||||
|
||||
// Skip if href is just "#"
|
||||
if (href === '#') {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = document.querySelector(href);
|
||||
|
||||
if (target) {
|
||||
e.preventDefault();
|
||||
|
||||
// Get header height for offset
|
||||
const header = document.getElementById('masthead');
|
||||
const headerHeight = header ? header.offsetHeight : 0;
|
||||
const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - 20;
|
||||
|
||||
window.scrollTo({
|
||||
top: targetPosition,
|
||||
behavior: prefersReducedMotion ? 'auto' : 'smooth'
|
||||
});
|
||||
|
||||
// Update URL hash
|
||||
if (history.pushState) {
|
||||
history.pushState(null, null, href);
|
||||
}
|
||||
|
||||
// Focus target element for accessibility
|
||||
target.setAttribute('tabindex', '-1');
|
||||
target.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard Navigation for Menus
|
||||
*/
|
||||
function setupKeyboardNavigation() {
|
||||
const menuItems = document.querySelectorAll('.primary-menu > li, .mobile-primary-menu > li');
|
||||
|
||||
menuItems.forEach(function(item) {
|
||||
const link = item.querySelector('a');
|
||||
const submenu = item.querySelector('.sub-menu');
|
||||
|
||||
if (!link || !submenu) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Open submenu on Enter/Space
|
||||
link.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
if (submenu) {
|
||||
e.preventDefault();
|
||||
toggleSubmenu(item, submenu);
|
||||
}
|
||||
}
|
||||
|
||||
// Close submenu on Escape
|
||||
if (e.key === 'Escape') {
|
||||
closeSubmenu(item, submenu);
|
||||
link.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// Close submenu when focus leaves
|
||||
const submenuLinks = submenu.querySelectorAll('a');
|
||||
if (submenuLinks.length > 0) {
|
||||
const lastSubmenuLink = submenuLinks[submenuLinks.length - 1];
|
||||
|
||||
lastSubmenuLink.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Tab' && !e.shiftKey) {
|
||||
closeSubmenu(item, submenu);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle submenu visibility
|
||||
*/
|
||||
function toggleSubmenu(item, submenu) {
|
||||
const isExpanded = item.classList.contains('submenu-open');
|
||||
|
||||
if (isExpanded) {
|
||||
closeSubmenu(item, submenu);
|
||||
} else {
|
||||
openSubmenu(item, submenu);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open submenu
|
||||
*/
|
||||
function openSubmenu(item, submenu) {
|
||||
item.classList.add('submenu-open');
|
||||
submenu.setAttribute('aria-hidden', 'false');
|
||||
|
||||
const firstLink = submenu.querySelector('a');
|
||||
if (firstLink) {
|
||||
firstLink.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close submenu
|
||||
*/
|
||||
function closeSubmenu(item, submenu) {
|
||||
item.classList.remove('submenu-open');
|
||||
submenu.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
|
||||
/**
|
||||
* Trap focus within mobile menu when open
|
||||
*/
|
||||
function setupFocusTrap() {
|
||||
const mobileMenu = document.getElementById('mobile-menu');
|
||||
|
||||
if (!mobileMenu) {
|
||||
return;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (!mobileMenu.classList.contains('active')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'Tab') {
|
||||
const focusableElements = mobileMenu.querySelectorAll(
|
||||
'a, button, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
|
||||
if (e.shiftKey) {
|
||||
// Shift + Tab
|
||||
if (document.activeElement === firstElement) {
|
||||
e.preventDefault();
|
||||
lastElement.focus();
|
||||
}
|
||||
} else {
|
||||
// Tab
|
||||
if (document.activeElement === lastElement) {
|
||||
e.preventDefault();
|
||||
firstElement.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize focus trap
|
||||
*/
|
||||
setupFocusTrap();
|
||||
|
||||
/**
|
||||
* Initialize when DOM is ready
|
||||
*/
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
})();
|
||||
27
Assets/Js/main.js
Normal file
27
Assets/Js/main.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* ROI THEME - MAIN JAVASCRIPT
|
||||
*
|
||||
* OPTIMIZACIÓN TBT Fase 2.3 (2025-11-27):
|
||||
* - Eliminado ~300 líneas de código muerto
|
||||
* - Removido: loadContactModal (modalContainer no existe)
|
||||
* - Removido: initContactForm (contactForm no existe)
|
||||
* - Removido: footerContactForm handler (ID incorrecto)
|
||||
* - Removido: TOC ScrollSpy duplicado (.toc-container no existe)
|
||||
* - Removido: smooth scroll duplicado (Bootstrap lo maneja)
|
||||
* - Removido: console.log de debug
|
||||
*
|
||||
* Código activo: Solo efecto scroll del navbar
|
||||
* Reducción: ~315 líneas → ~25 líneas
|
||||
*/
|
||||
|
||||
// Navbar scroll effect - adds 'scrolled' class when user scrolls
|
||||
window.addEventListener('scroll', function() {
|
||||
const navbar = document.querySelector('.navbar');
|
||||
if (navbar) {
|
||||
if (window.scrollY > 50) {
|
||||
navbar.classList.add('scrolled');
|
||||
} else {
|
||||
navbar.classList.remove('scrolled');
|
||||
}
|
||||
}
|
||||
});
|
||||
464
Assets/Js/modal-contact.js
Normal file
464
Assets/Js/modal-contact.js
Normal file
@@ -0,0 +1,464 @@
|
||||
/**
|
||||
* Modal de Contacto - JavaScript
|
||||
*
|
||||
* Carga dinámica del modal, validaciones y envío a webhook
|
||||
* Compatible con Bootstrap 5.3.2
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// =========================================================================
|
||||
// CONFIGURACIÓN
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* URL del webhook para envío de formulario
|
||||
* IMPORTANTE: Reemplaza con tu URL real de webhook
|
||||
*
|
||||
* Servicios recomendados:
|
||||
* - Make (Integromat): https://www.make.com
|
||||
* - Zapier: https://zapier.com
|
||||
* - Webhook.site (testing): https://webhook.site
|
||||
* - n8n (self-hosted): https://n8n.io
|
||||
* - Pipedream: https://pipedream.com
|
||||
*/
|
||||
const WEBHOOK_URL = 'https://webhook.site/tu-url-aqui';
|
||||
|
||||
/**
|
||||
* Expresión regular para validación de email
|
||||
*/
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
/**
|
||||
* Expresión regular para validación de WhatsApp
|
||||
* Acepta 10-15 dígitos con o sin espacios/guiones
|
||||
*/
|
||||
const WHATSAPP_REGEX = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,4}[-\s\.]?[0-9]{1,5}$/;
|
||||
|
||||
// =========================================================================
|
||||
// INICIALIZACIÓN
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Inicializa el modal cuando el DOM está listo
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadContactModal();
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
// CARGA DINÁMICA DEL MODAL
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Carga el HTML del modal dinámicamente desde archivo externo
|
||||
*/
|
||||
function loadContactModal() {
|
||||
// Verificar si ya existe el contenedor del modal
|
||||
let modalContainer = document.getElementById('modalContainer');
|
||||
|
||||
if (!modalContainer) {
|
||||
// Crear contenedor si no existe
|
||||
modalContainer = document.createElement('div');
|
||||
modalContainer.id = 'modalContainer';
|
||||
document.body.appendChild(modalContainer);
|
||||
}
|
||||
|
||||
// Obtener la URL del tema desde WordPress
|
||||
const themeUrl = typeof roiheme !== 'undefined' && rroieme.themeUrl
|
||||
? roiheme.themeUrl
|
||||
: '/wp-content/themes/roitheme';
|
||||
|
||||
// Cargar el HTML del modal
|
||||
fetch(themeUrl + '/modal-contact.html')
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Error al cargar el modal: ' + response.status);
|
||||
}
|
||||
return response.text();
|
||||
})
|
||||
.then(html => {
|
||||
modalContainer.innerHTML = html;
|
||||
|
||||
// Inicializar el formulario después de cargar el HTML
|
||||
initContactForm();
|
||||
|
||||
console.log('Modal de contacto cargado exitosamente');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error cargando el modal:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// VALIDACIONES
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Valida el campo de nombre completo
|
||||
* @param {string} fullName - Nombre a validar
|
||||
* @returns {Object} - {valid: boolean, message: string}
|
||||
*/
|
||||
function validateFullName(fullName) {
|
||||
if (!fullName || fullName.trim().length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'Por favor ingresa tu nombre completo'
|
||||
};
|
||||
}
|
||||
if (fullName.trim().length < 3) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'El nombre debe tener al menos 3 caracteres'
|
||||
};
|
||||
}
|
||||
return { valid: true, message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida el campo de email
|
||||
* @param {string} email - Email a validar
|
||||
* @returns {Object} - {valid: boolean, message: string}
|
||||
*/
|
||||
function validateEmail(email) {
|
||||
if (!email || email.trim().length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'Por favor ingresa tu correo electrónico'
|
||||
};
|
||||
}
|
||||
if (!EMAIL_REGEX.test(email.trim())) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'Por favor ingresa un correo electrónico válido'
|
||||
};
|
||||
}
|
||||
return { valid: true, message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida el campo de WhatsApp
|
||||
* @param {string} whatsapp - Número de WhatsApp a validar
|
||||
* @returns {Object} - {valid: boolean, message: string}
|
||||
*/
|
||||
function validateWhatsApp(whatsapp) {
|
||||
if (!whatsapp || whatsapp.trim().length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'Por favor ingresa tu número de WhatsApp'
|
||||
};
|
||||
}
|
||||
|
||||
// Remover todos los caracteres no numéricos excepto el +
|
||||
const cleanNumber = whatsapp.replace(/[^\d+]/g, '');
|
||||
const digitsOnly = cleanNumber.replace(/\+/g, '');
|
||||
|
||||
if (digitsOnly.length < 10 || digitsOnly.length > 15) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'El número debe tener entre 10 y 15 dígitos'
|
||||
};
|
||||
}
|
||||
|
||||
if (!WHATSAPP_REGEX.test(whatsapp)) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'Por favor ingresa un número de WhatsApp válido'
|
||||
};
|
||||
}
|
||||
|
||||
return { valid: true, message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Marca un campo como válido o inválido visualmente
|
||||
* @param {HTMLElement} input - Elemento input
|
||||
* @param {boolean} isValid - Si es válido o no
|
||||
* @param {string} message - Mensaje de error (opcional)
|
||||
*/
|
||||
function setFieldValidation(input, isValid, message = '') {
|
||||
if (isValid) {
|
||||
input.classList.remove('is-invalid');
|
||||
input.classList.add('is-valid');
|
||||
} else {
|
||||
input.classList.remove('is-valid');
|
||||
input.classList.add('is-invalid');
|
||||
|
||||
// Actualizar mensaje de error
|
||||
const feedback = input.nextElementSibling;
|
||||
if (feedback && feedback.classList.contains('invalid-feedback')) {
|
||||
feedback.textContent = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limpia las validaciones visuales de un campo
|
||||
* @param {HTMLElement} input - Elemento input
|
||||
*/
|
||||
function clearFieldValidation(input) {
|
||||
input.classList.remove('is-valid', 'is-invalid');
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FORMULARIO
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Inicializa el formulario de contacto con validación y envío a webhook
|
||||
*/
|
||||
function initContactForm() {
|
||||
const contactForm = document.getElementById('contactForm');
|
||||
|
||||
if (!contactForm) {
|
||||
console.error('Formulario de contacto no encontrado');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validación en tiempo real
|
||||
const fullNameInput = document.getElementById('fullName');
|
||||
const emailInput = document.getElementById('email');
|
||||
const whatsappInput = document.getElementById('whatsapp');
|
||||
|
||||
if (fullNameInput) {
|
||||
fullNameInput.addEventListener('blur', function() {
|
||||
const validation = validateFullName(this.value);
|
||||
setFieldValidation(this, validation.valid, validation.message);
|
||||
});
|
||||
|
||||
fullNameInput.addEventListener('input', function() {
|
||||
if (this.classList.contains('is-invalid')) {
|
||||
const validation = validateFullName(this.value);
|
||||
if (validation.valid) {
|
||||
setFieldValidation(this, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (emailInput) {
|
||||
emailInput.addEventListener('blur', function() {
|
||||
const validation = validateEmail(this.value);
|
||||
setFieldValidation(this, validation.valid, validation.message);
|
||||
});
|
||||
|
||||
emailInput.addEventListener('input', function() {
|
||||
if (this.classList.contains('is-invalid')) {
|
||||
const validation = validateEmail(this.value);
|
||||
if (validation.valid) {
|
||||
setFieldValidation(this, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (whatsappInput) {
|
||||
whatsappInput.addEventListener('blur', function() {
|
||||
const validation = validateWhatsApp(this.value);
|
||||
setFieldValidation(this, validation.valid, validation.message);
|
||||
});
|
||||
|
||||
whatsappInput.addEventListener('input', function() {
|
||||
if (this.classList.contains('is-invalid')) {
|
||||
const validation = validateWhatsApp(this.value);
|
||||
if (validation.valid) {
|
||||
setFieldValidation(this, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Manejo del envío del formulario
|
||||
contactForm.addEventListener('submit', handleFormSubmit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maneja el envío del formulario
|
||||
* @param {Event} e - Evento de submit
|
||||
*/
|
||||
async function handleFormSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
// Obtener elementos del formulario
|
||||
const fullNameInput = document.getElementById('fullName');
|
||||
const companyInput = document.getElementById('company');
|
||||
const whatsappInput = document.getElementById('whatsapp');
|
||||
const emailInput = document.getElementById('email');
|
||||
const commentsInput = document.getElementById('comments');
|
||||
const submitButton = e.target.querySelector('button[type="submit"]');
|
||||
|
||||
// Validar todos los campos
|
||||
const fullNameValidation = validateFullName(fullNameInput.value);
|
||||
const emailValidation = validateEmail(emailInput.value);
|
||||
const whatsappValidation = validateWhatsApp(whatsappInput.value);
|
||||
|
||||
// Marcar campos inválidos
|
||||
setFieldValidation(fullNameInput, fullNameValidation.valid, fullNameValidation.message);
|
||||
setFieldValidation(emailInput, emailValidation.valid, emailValidation.message);
|
||||
setFieldValidation(whatsappInput, whatsappValidation.valid, whatsappValidation.message);
|
||||
|
||||
// Si algún campo es inválido, detener el envío
|
||||
if (!fullNameValidation.valid || !emailValidation.valid || !whatsappValidation.valid) {
|
||||
showFormMessage('Por favor corrige los errores en el formulario', 'danger');
|
||||
|
||||
// Hacer foco en el primer campo inválido
|
||||
if (!fullNameValidation.valid) {
|
||||
fullNameInput.focus();
|
||||
} else if (!emailValidation.valid) {
|
||||
emailInput.focus();
|
||||
} else if (!whatsappValidation.valid) {
|
||||
whatsappInput.focus();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Preparar datos del formulario
|
||||
const formData = {
|
||||
fullName: fullNameInput.value.trim(),
|
||||
company: companyInput.value.trim(),
|
||||
whatsapp: whatsappInput.value.trim(),
|
||||
email: emailInput.value.trim(),
|
||||
comments: commentsInput.value.trim(),
|
||||
timestamp: new Date().toISOString(),
|
||||
source: 'APU Website - Modal Contact Form'
|
||||
};
|
||||
|
||||
// Deshabilitar botón y mostrar spinner
|
||||
const originalButtonText = submitButton.innerHTML;
|
||||
submitButton.disabled = true;
|
||||
submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Enviando...';
|
||||
|
||||
try {
|
||||
// Enviar datos al webhook
|
||||
const response = await fetch(WEBHOOK_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
mode: 'no-cors' // Permite envío sin CORS (no podremos leer la respuesta)
|
||||
});
|
||||
|
||||
// Como usamos no-cors, asumimos que el envío fue exitoso si no hay error
|
||||
showFormMessage('¡Mensaje enviado exitosamente! Nos pondremos en contacto pronto.', 'success');
|
||||
|
||||
// Resetear formulario
|
||||
e.target.reset();
|
||||
|
||||
// Limpiar validaciones visuales
|
||||
clearFieldValidation(fullNameInput);
|
||||
clearFieldValidation(emailInput);
|
||||
clearFieldValidation(whatsappInput);
|
||||
|
||||
// Tracking de Google Analytics 4
|
||||
if (typeof gtag !== 'undefined') {
|
||||
gtag('event', 'form_submission', {
|
||||
event_category: 'Contact Form',
|
||||
event_label: 'Modal Contact Form Submitted',
|
||||
value: 1
|
||||
});
|
||||
}
|
||||
|
||||
// Cerrar modal después de 2 segundos
|
||||
setTimeout(() => {
|
||||
const modalElement = document.getElementById('contactModal');
|
||||
if (modalElement && typeof bootstrap !== 'undefined') {
|
||||
const modal = bootstrap.Modal.getInstance(modalElement);
|
||||
if (modal) {
|
||||
modal.hide();
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error al enviar el formulario:', error);
|
||||
showFormMessage('Hubo un error al enviar el mensaje. Por favor intenta nuevamente.', 'danger');
|
||||
} finally {
|
||||
// Rehabilitar botón
|
||||
submitButton.disabled = false;
|
||||
submitButton.innerHTML = originalButtonText;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Muestra un mensaje de feedback en el formulario
|
||||
* @param {string} message - Mensaje a mostrar
|
||||
* @param {string} type - Tipo de alerta (success, danger, warning, info)
|
||||
*/
|
||||
function showFormMessage(message, type) {
|
||||
const messageDiv = document.getElementById('formMessage');
|
||||
|
||||
if (!messageDiv) {
|
||||
console.error('Contenedor de mensajes no encontrado');
|
||||
return;
|
||||
}
|
||||
|
||||
messageDiv.className = `mt-3 alert alert-${type}`;
|
||||
messageDiv.textContent = message;
|
||||
messageDiv.style.display = 'block';
|
||||
messageDiv.setAttribute('role', 'alert');
|
||||
|
||||
// Anunciar mensaje a lectores de pantalla
|
||||
messageDiv.setAttribute('aria-live', 'polite');
|
||||
|
||||
// Ocultar mensaje después de 5 segundos (excepto mensajes de éxito)
|
||||
if (type !== 'success') {
|
||||
setTimeout(() => {
|
||||
messageDiv.style.display = 'none';
|
||||
}, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// EVENTOS DEL MODAL
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Limpia el formulario cuando se cierra el modal
|
||||
*/
|
||||
document.addEventListener('hidden.bs.modal', function (event) {
|
||||
if (event.target.id === 'contactModal') {
|
||||
const contactForm = document.getElementById('contactForm');
|
||||
const messageDiv = document.getElementById('formMessage');
|
||||
|
||||
if (contactForm) {
|
||||
contactForm.reset();
|
||||
|
||||
// Limpiar validaciones visuales
|
||||
const inputs = contactForm.querySelectorAll('.form-control');
|
||||
inputs.forEach(input => clearFieldValidation(input));
|
||||
}
|
||||
|
||||
if (messageDiv) {
|
||||
messageDiv.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Tracking cuando se abre el modal
|
||||
*/
|
||||
document.addEventListener('shown.bs.modal', function (event) {
|
||||
if (event.target.id === 'contactModal') {
|
||||
// Hacer foco en el primer campo
|
||||
const fullNameInput = document.getElementById('fullName');
|
||||
if (fullNameInput) {
|
||||
setTimeout(() => fullNameInput.focus(), 100);
|
||||
}
|
||||
|
||||
// Google Analytics 4 tracking
|
||||
if (typeof gtag !== 'undefined') {
|
||||
gtag('event', 'modal_open', {
|
||||
event_category: 'Contact Form',
|
||||
event_label: 'Contact Modal Opened',
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
})();
|
||||
148
Assets/Js/notification-bar.js
Normal file
148
Assets/Js/notification-bar.js
Normal file
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Top Notification Bar Script
|
||||
* Issue #39
|
||||
*
|
||||
* Maneja el cierre de la barra de notificación y el almacenamiento
|
||||
* de la preferencia del usuario mediante cookies.
|
||||
*
|
||||
* @package ROI_Theme
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Inicialización cuando el DOM está listo
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
initNotificationBar();
|
||||
});
|
||||
|
||||
/**
|
||||
* Inicializa la funcionalidad de la barra de notificación
|
||||
*/
|
||||
function initNotificationBar() {
|
||||
const notificationBar = document.getElementById('topNotificationBar');
|
||||
const closeBtn = document.querySelector('.btn-close-notification');
|
||||
const navbar = document.querySelector('.navbar');
|
||||
|
||||
// Verificar que existan los elementos necesarios
|
||||
if (!notificationBar || !closeBtn) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Event listener para el botón de cerrar
|
||||
closeBtn.addEventListener('click', function() {
|
||||
closeNotificationBar(notificationBar, navbar);
|
||||
});
|
||||
|
||||
// Permitir cerrar con la tecla Escape
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape' && notificationBar.style.display !== 'none') {
|
||||
closeNotificationBar(notificationBar, navbar);
|
||||
}
|
||||
});
|
||||
|
||||
// Ajustar el scroll inicial si la barra está visible
|
||||
adjustInitialScroll(notificationBar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cierra la barra de notificación con animación
|
||||
*
|
||||
* @param {HTMLElement} notificationBar - Elemento de la barra de notificación
|
||||
* @param {HTMLElement} navbar - Elemento del navbar
|
||||
*/
|
||||
function closeNotificationBar(notificationBar, navbar) {
|
||||
// Ocultar barra con animación de slide up
|
||||
notificationBar.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
|
||||
notificationBar.style.transform = 'translateY(-100%)';
|
||||
notificationBar.style.opacity = '0';
|
||||
|
||||
// Esperar a que termine la animación antes de ocultar completamente
|
||||
setTimeout(function() {
|
||||
notificationBar.style.display = 'none';
|
||||
document.body.classList.add('notification-dismissed');
|
||||
|
||||
// Ajustar navbar suavemente
|
||||
if (navbar) {
|
||||
navbar.style.transition = 'top 0.3s ease';
|
||||
navbar.style.top = '0';
|
||||
}
|
||||
|
||||
// Guardar cookie por 7 días
|
||||
setCookie('roinotification_dismissed', '1', 7);
|
||||
|
||||
// Disparar evento personalizado para otros scripts
|
||||
const event = new CustomEvent('notificationBarClosed', {
|
||||
detail: { timestamp: Date.now() }
|
||||
});
|
||||
document.dispatchEvent(event);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* Establece una cookie con nombre, valor y días de expiración
|
||||
*
|
||||
* @param {string} name - Nombre de la cookie
|
||||
* @param {string} value - Valor de la cookie
|
||||
* @param {number} days - Días hasta la expiración
|
||||
*/
|
||||
function setCookie(name, value, days) {
|
||||
const expiryDate = new Date();
|
||||
expiryDate.setDate(expiryDate.getDate() + days);
|
||||
|
||||
const cookie = name + '=' + encodeURIComponent(value) +
|
||||
'; expires=' + expiryDate.toUTCString() +
|
||||
'; path=/' +
|
||||
'; SameSite=Lax';
|
||||
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajusta el scroll inicial para compensar la altura de la barra
|
||||
*
|
||||
* @param {HTMLElement} notificationBar - Elemento de la barra de notificación
|
||||
*/
|
||||
function adjustInitialScroll(notificationBar) {
|
||||
// Si hay un hash en la URL, reajustar el scroll para compensar la altura
|
||||
if (window.location.hash) {
|
||||
setTimeout(function() {
|
||||
const target = document.querySelector(window.location.hash);
|
||||
if (target) {
|
||||
const barHeight = notificationBar.offsetHeight;
|
||||
const navbarHeight = document.querySelector('.navbar')?.offsetHeight || 0;
|
||||
const offset = barHeight + navbarHeight;
|
||||
|
||||
window.scrollTo({
|
||||
top: target.offsetTop - offset,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Función helper para obtener el valor de una cookie
|
||||
*
|
||||
* @param {string} name - Nombre de la cookie
|
||||
* @return {string|null} - Valor de la cookie o null si no existe
|
||||
*/
|
||||
function getCookie(name) {
|
||||
const nameEQ = name + '=';
|
||||
const cookies = document.cookie.split(';');
|
||||
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
let cookie = cookies[i].trim();
|
||||
if (cookie.indexOf(nameEQ) === 0) {
|
||||
return decodeURIComponent(cookie.substring(nameEQ.length));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
})();
|
||||
Reference in New Issue
Block a user