Create a Live Highway Traffic Rotator using JavaScript – RSS / XML
In this video tutorial, you are going to learn how to manipulate XML data using JavaScript. I tried to explain every step of creating this RSS rotator. If you have any questions or ideas I would love to hear from you!
Html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>RSS Live Traffic Rotator</title> <link rel="stylesheet" href="/css/styles.css"> </head> <body> <div class="rss-rotator"> <div class="title">Traffic Rotator</div> <ul id="item"></ul> </div> <script src="js/script.js"></script> </body> </html>
SCSS
@import url('https://fonts.googleapis.com/css?family=Quicksand:400,700&display=swap'); $primary-color: #396362; $secondary-color: #4b8e8d; body { margin: 0; display: flex; height: 100vh; font-family: 'Quicksand', sans-serif; background-image: url("../img/bg.jpg"); background-size: cover; background-position: 0px -100px; } div.rss-rotator { width: 100%; align-self: flex-end; background-color: #fff; .title { padding: 20px; background-color: $primary-color; color: #fff; } ul { list-style: none; height: 300px; overflow: auto; margin: 0; padding: 0; li { padding: 0 20px; border-bottom: 1px solid #ccc; } } }
JavaScript
loadXMLFeed = () => { const url = "http://m.highwaysengland.co.uk/feeds/rss/UnplannedEvents.xml"; fetch(url) .then(response=>response.text()) .then(data=> { let parser = new DOMParser(); let xml = parser.parseFromString(data, "application/xml"); displayTrafficList(xml); }); } document.addEventListener("DOMContentLoaded", loadXMLFeed); function displayTrafficList(x) { console.log(x); let list = document.getElementById('item'); let item = x.getElementsByTagName('item'); let itemNum = x.getElementsByTagName('item').length; if(itemNum === 0){ list.innerHTML = "<li><h3>No Planned Roadworks...</h3></li>" setTimeout(function(){ loadXMLFeed(); console.log("No new data..."); }, 7000); } else { for(let i=0; i<itemNum; i++) { let li = document.createElement('li'); li.className = "listItem"; li.innerHTML = ` <h3>${item[i].getElementsByTagName('title')[0].innerHTML}</h3> <p>${item[i].getElementsByTagName('description')[0].innerHTML}</p> `; list.appendChild(li); } } setTimeout(function(){ startAnimation(item); }, 7000); } startAnimation = (x) => { let listItem = document.getElementsByClassName('listItem'); for(let i=0; i<x.length; i++) { setTimeout(function(){ listItem[0].remove(); if(i == x.length -1) { loadXMLFeed(); console.log("Loading new data..."); } }, i*3000); } }