Como insertar un Breaking News en Blogger
📢 Cómo Insertar un Breaking News en Blogger con un Widget | Guía Definitiva
🌟 ¿Por Qué Usar un Widget Breaking News en tu Blog?
Un banner de noticias destacadas es esencial para blogs que publican contenido actualizado frecuentemente. Con este widget lograrás:
- Captar la atención inmediata de tus visitantes
- Destacar tus publicaciones más importantes
- Mejorar la navegación con enlaces directos
- Añadir dinamismo profesional sin afectar la velocidad
A continuación puede ver su demostración en el siguiente blog de demos
🚀 Cómo Insertar el Breaking News como Widget en Blogger
📌 Paso 1: Accede a la sección de Widgets
- Entra a tu panel de Blogger
- Ve a "Diseño" → "Añadir un gadget"
- Selecciona "HTML/JavaScript"
📌 Paso 2: Copia y Pega el Código Completo
Inserta este código optimizado en el widget:
<div id='breakingnews'>
<span class='tulisbreaking'>ÚLTIMAS NOTICIAS</span>
<div class='news-container'>
<div id='recentpostbreaking'>Cargando noticias...</div>
</div>
</div>
<style type='text/css'>
/* Estilo principal del contenedor */
#breakingnews {
background: linear-gradient(90deg, #1a2a6c, #b21f1f, #fdbb2d);
color: white;
padding: 12px 15px;
border-radius: 8px;
margin: 15px 0;
display: flex;
align-items: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
position: relative;
overflow: hidden;
}
/* Efecto de gradiente animado */
#breakingnews::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg,
rgba(255,255,255,0) 0%,
rgba(255,255,255,0.2) 50%,
rgba(255,255,255,0) 100%);
animation: shine 3s infinite;
z-index: 0;
}
@keyframes shine {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
/* Estilo del título "Breaking News" */
#breakingnews .tulisbreaking {
background: rgba(0, 0, 0, 0.7);
padding: 5px 12px;
border-radius: 20px;
font-weight: bold;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 1px;
margin-right: 15px;
flex-shrink: 0;
z-index: 1;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
/* Contenedor de noticias */
.news-container {
flex-grow: 1;
overflow: hidden;
position: relative;
height: 25px;
z-index: 1;
}
#recentpostbreaking {
position: absolute;
white-space: nowrap;
width: 100%;
height: 100%;
display: flex;
align-items: center;
}
/* Estilo de la lista de noticias */
#recentpostbreaking ul {
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
}
#recentpostbreaking li {
margin-right: 30px;
opacity: 0;
position: absolute;
right: 0;
transform: translateX(100%);
transition: none;
}
#recentpostbreaking li.active {
position: relative;
opacity: 1;
transform: translateX(0);
transition: all 0.5s ease-in-out;
}
#recentpostbreaking li.exiting {
opacity: 0;
transform: translateX(-100%);
transition: all 0.5s ease-in-out;
}
#recentpostbreaking a {
color: white;
text-decoration: none;
font-weight: 500;
font-size: 15px;
text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
#recentpostbreaking a:hover {
color: #fffc00;
text-decoration: underline;
}
/* Indicador de noticias (opcional) */
.news-indicator {
display: flex;
gap: 5px;
margin-left: 15px;
}
.news-indicator span {
width: 8px;
height: 8px;
background: rgba(255,255,255,0.3);
border-radius: 50%;
display: block;
}
.news-indicator span.active {
background: white;
}
</style>
<script type='text/javascript'>
//<![CDATA[
(function() {
var recentPostsContainer = document.getElementById('recentpostbreaking');
var maxPosts = 5; // Número máximo de posts a mostrar
var currentIndex = 0;
var newsItems = [];
var intervalId = null;
// Función para mostrar las noticias
function displayPosts(posts) {
if (!posts || posts.length === 0) {
recentPostsContainer.innerHTML = '<span>No hay noticias recientes</span>';
return;
}
// Limpiar el contenedor
recentPostsContainer.innerHTML = '';
// Crear lista
var ul = document.createElement('ul');
newsItems = [];
// Crear elementos de noticias
posts.forEach(function(post, index) {
var li = document.createElement('li');
var a = document.createElement('a');
a.href = post.url;
a.textContent = post.title;
a.target = '_blank';
li.appendChild(a);
ul.appendChild(li);
newsItems.push(li);
// Mostrar el primer item
if (index === 0) {
li.classList.add('active');
}
});
recentPostsContainer.appendChild(ul);
// Iniciar el carrusel si hay más de una noticia
if (posts.length > 1) {
startNewsCarousel();
}
}
// Función para cambiar a la siguiente noticia
function showNextNews() {
// Salir si no hay items
if (newsItems.length === 0) return;
// Ocultar el item actual
var currentItem = newsItems[currentIndex];
currentItem.classList.remove('active');
currentItem.classList.add('exiting');
// Calcular el siguiente índice
currentIndex = (currentIndex + 1) % newsItems.length;
// Mostrar el nuevo item
setTimeout(function() {
currentItem.classList.remove('exiting');
var nextItem = newsItems[currentIndex];
nextItem.classList.add('active');
}, 500);
}
// Iniciar el carrusel de noticias
function startNewsCarousel() {
// Limpiar intervalo anterior si existe
if (intervalId) clearInterval(intervalId);
// Cambiar de noticia cada 4 segundos
intervalId = setInterval(showNextNews, 4000);
}
// Función principal para obtener las noticias
function fetchPostsPrimary() {
try {
// Usar la API interna de Blogger si está disponible
if (typeof _WidgetManager !== 'undefined' &&
_WidgetManager._GetAllData &&
_WidgetManager._GetAllData().blog &&
_WidgetManager._GetAllData().blog.posts) {
var blogPosts = _WidgetManager._GetAllData().blog.posts;
var posts = blogPosts.slice(0, maxPosts).map(function(post) {
return {
url: post.url,
title: post.title
};
});
displayPosts(posts);
} else {
fetchPostsAlternative();
}
} catch (e) {
console.error('Error:', e);
recentPostsContainer.innerHTML = 'Cargando noticias...';
fetchPostsAlternative();
}
}
// Método alternativo usando el feed
function fetchPostsAlternative() {
var blogHomepageUrl = "<data:blog.homepageUrl/>";
if (blogHomepageUrl === "" || blogHomepageUrl.startsWith("<data:")) {
blogHomepageUrl = window.location.origin;
}
var feedUrl = blogHomepageUrl.replace(/^http:/, 'https:') + '/feeds/posts/default?alt=json&max-results=' + maxPosts;
fetch(feedUrl)
.then(function(response) {
if (!response.ok) throw new Error('Error en la red');
return response.json();
})
.then(function(data) {
if (data.feed && data.feed.entry) {
var posts = data.feed.entry.map(function(entry) {
var postUrl = entry.link.find(function(link) {
return link.rel === 'alternate';
})?.href || '#';
return {
url: postUrl,
title: entry.title.$t
};
});
displayPosts(posts);
} else {
recentPostsContainer.innerHTML = 'No hay noticias disponibles';
}
})
.catch(function(error) {
console.error('Error:', error);
recentPostsContainer.innerHTML = 'Error al cargar noticias';
});
}
// Iniciar cuando el DOM esté listo
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fetchPostsPrimary);
} else {
fetchPostsPrimary();
}
})();
//]]>
</script>
💡 Nota importante: Este código está diseñado para funcionar en cualquier parte del blog al ser insertado como widget independiente.
🎨 Personalización Avanzada del Widget
🔧 Cambios Básicos
- Texto del título: Edita
ÚLTIMAS NOTICIASpor tu propio texto - Número de posts: Modifica
var maxPosts = 5según necesites - Velocidad: Ajusta
4000ensetInterval(showNextNews, 4000)(valor en milisegundos)
🎚️ Ajustes de Diseño Profesional
/* Cambia la paleta de colores del gradiente */
background: linear-gradient(90deg, #1a2a6c, #b21f1f, #fdbb2d);
/* Ajusta el estilo del texto */
#recentpostbreaking a {
font-size: 15px; /* Tamaño de fuente */
font-family: 'Roboto', sans-serif; /* Tipografía */
}
⚡ Optimización SEO para el Breaking News
Maximiza el impacto en buscadores con estos tips:
- Usa palabras clave en los títulos de tus posts destacados
- Enlaza contenido relevante para mejorar la estructura de enlaces internos
- Mantén actualizadas las noticias mostradas
- Aprovecha el rich snippet con schema markup (opcional)
❓ Preguntas Frecuentes
¿Funciona en móviles?
✅ Sí, el diseño es 100% responsive y se adapta a cualquier dispositivo.
¿Puedo mostrar más de 5 noticias?
¡Claro! Solo modifica var maxPosts = 5 por el número deseado.
¿Cómo cambio la posición del widget?
Simplemente arrastra el gadget en la sección "Diseño" de Blogger a tu ubicación preferida.
🔚 Conclusión
Ahora tienes un sistema de Breaking News profesional que:
- Se instala en 2 minutos como widget
- Muestra noticias con efectos visuales atractivos
- Es totalmente personalizable
- Mejora la experiencia de usuario
¿Viste lo fácil que fue? ¡No esperes más para darle ese toque profesional a tu blog! 🚀
¿Necesitas ayuda personalizada? ¡Déjame un comentario con tus dudas!
8 comentarios: