Things to improve in your code:
- removes the HTML CSS
- separates the logic of changing news from ajax
- creates HTML outside the news generator
Suggestion:
Use a function like this:
var alternador = (function(el, delay) {
el = $(el);
var noticias = [];
var p = el.find('p');
var a = el.find('a');
var index = 0;
function mostrarProxima() {
el.fadeIn();
var value = noticias[index++];
a.html(value.title);
a.attr('href', value.link);
// p.html(value.content); // <- caso queiras usar mais tarde
el.delay(2000).fadeOut();
if (index == noticias.length) index = 0;
}
setInterval(mostrarProxima, delay || 3000);
return function(_noticias) {
noticias = _noticias;
}
})('#result', 5000);
and then inside ajax you only have to update the news if you need a refresh, like this:
values = xml.responseData.feed.entries;
alternador(values);
Example:
$(function() {
var alternador = (function(el, delay) {
el = $(el);
var noticias = [];
var p = el.find('p');
var a = el.find('a');
var index = 0;
function mostrarProxima() {
el.fadeIn();
var value = noticias[index++];
a.html(value.title);
a.attr('href', value.link);
// p.html(value.content); // <- caso queiras usar mais tarde
el.delay(2000).fadeOut();
if (index == noticias.length) index = 0;
}
setInterval(mostrarProxima, delay || 3000);
return function(_noticias) {
noticias = _noticias;
}
})('#result', 5000);
var urlRss = 'http://www.cidades.gov.br/ultimas-noticias?format=feed&type=rss';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(urlRss),
dataType: 'json',
error: function(xhr) {
var erro = xhr.responseText;
alert('Erro ao ler o feed: ' + erro);
},
success: function(xml) {
values = xml.responseData.feed.entries;
alternador(values);
}
});
});
#result li {
list-style: none;
}
#result a {
text-decoration: none;
color: #fff;
}
#footer {
background-color: #224B9D;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
color: white;
font-weight: bold;
padding: 1em;
height: 4em;
}
#titulo {
background-color: #F95252;
color: white;
font-weight: bold;
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
float: left;
text-align: center;
}
#header {
color: white;
font-weight: bold;
background-color: #7E9DBB;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
#header:after {
content: " ";
display: block;
clear: both;
}
#header > div {
padding: 1em;
}
<body>
<div id="header">
<div id="titulo">
::Noticias::
</div>
<div>
Título
</div>
</div>
<div id="footer" ¨>
<ul id="result">
<li>
<a href=""></a>
<p></p>
</li>
</ul>
</div>
</body>
Thank you Sergio, I will do this and update the code on Github! Thank you very much!
– MiguelCPJava
I changed on github, with some modifications, I’m already registering issues. Thanks!
– MiguelCPJava