Jump to content
Killersites Community
Sign in to follow this  
andrew1702

Javascript Rss Feed Widget

Recommended Posts


Hi there!
 
Please can anyone reading this post who has a good understanding of Javascript/jQuery/Ajax etc. etc. explain whether it's possible to adapt the source code I have inserted below (which was working fine) to work with the Yahoo API (or Bing API - if they have one) instead of the now depreciated Google API.
 
I have spent many hours researching the web for a solution to this problem - a solution that is simple for me to understand, but have (so far) been unable to find a fix.
 
In addition to the source code inserted into my web page where the RSS Widget is to display, this plugin comes with tsc_vticker.js and tsc_rssfeed.js.  I suspect the changes to which I refer need only to be made to tsc_rssfeed.js, but this is only a guess.  Just to be on the safe side I'll post all other source code for reference purposes.
 
I have a fair grasp of HTML, but no understanding of JS or jQuery (let alone Ajax) so please be aware that any explanation of how to adapt this code should be made as simple as possible and ideally include examples of the code before and after its alteration.
 
A couple of other questions.
 
When Google switched off the Feed API, would I have been able to keep my Widget working if I'd previously downloaded and hosted the API on my own server, as might be the case with externally hosted versus locally hosted Javascripts/jQuery, or is this not something that is possible with an API?  Should Yahoo depreciate their RSS API, is there any other way to easily include multiple Widgets on my page/s without the need to rely on external services that limit the number of feeds I can display, charge for the service, or could shut it down at any time?
 
From all of the above, you can probably see that my understanding of such matters is limited, so please excuse my ignorance.
 
Nevertheless, any constructive replies on this topic would be greatly appreciated.
 
TSC_RSSFEED.JS
 
/**
 * Plugin: jquery.zRSSFeed
 *
 * Version: 1.1.5
 * (c) Copyright 2010-2011, Zazar Ltd
 *
 * Description: jQuery plugin for display of RSS feeds via Google Feed API
 *              (Based on original plugin jGFeed by jQuery HowTo. Filesize function by Cary Dunn.)
 *
 * History:
 * 1.1.5 - Target option now applies to all feed links
 * 1.1.4 - Added option to hide media and now compressed with Google Closure
 * 1.1.3 - Check for valid published date
 * 1.1.2 - Added user callback function due to issue with ajaxStop after jQuery 1.4.2
 * 1.1.1 - Correction to null xml entries and support for media with jQuery < 1.5
 * 1.1.0 - Added support for media in enclosure tags
 * 1.0.3 - Added feed link target
 * 1.0.2 - Fixed issue with GET parameters (Seb Dangerfield) and SSL option
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/
 
(function($){
 
    $.fn.rssfeed = function(url, options, fn) {
 
        // Set pluign defaults
        var defaults = {
            limit: 50,
            header: true,
            titletag: 'h4',
            date: true,
            content: true,
            snippet: true,
            media: true,
            showerror: true,
            errormsg: '',
            key: null,
            ssl: false,
            linktarget: '_blank'
        };
        var options = $.extend(defaults, options);
     
        // Functions
        return this.each(function(i, e) {
            var $e = $(e);
            var s = '';
 
            // Check for SSL protocol
            if (options.ssl) s = 's';
         
            // Add feed class to user div
            if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
         
            // Check for valid url
            if(url == null) return false;
         
            // Create Google Feed API address
            var api = "http"+ s +"://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
            if (options.limit != null) api += "&num=" + options.limit;
            if (options.key != null) api += "&key=" + options.key;
            api += "&output=json_xml"
 
            // Send request
            $.getJSON(api, function(data){
             
                // Check for error
                if (data.responseStatus == 200) {
 
                    // Process the feeds
                    _process(e, data.responseData, options);
 
                    // Optional user callback function
                    if ($.isFunction(fn)) fn.call(this,$e);
                 
                } else {
 
                    // Handle error if required
                    if (options.showerror)
                        if (options.errormsg != '') {
                            var msg = options.errormsg;
                        } else {
                            var msg = data.responseDetails;
                        };
                        $(e).html('<div class="rssError"><p>'+ msg +'</p></div>');
                };
            });            
        });
    };
 
    // Function to create HTML result
    var _process = function(e, data, options) {
 
        // Get JSON feed data
        var feeds = data.feed;
        if (!feeds) {
            return false;
        }
        var html = '';
        var row = 'odd';
     
        // Get XML data for media (parseXML not used as requires 1.5+)
        if (options.media) {
            var xml = getXMLDocument(data.xmlString);
            var xmlEntries = xml.getElementsByTagName('item');
        }
     
        // Add header if required
        if (options.header)
            html +=    '<div class="rssHeader">' +
                '<a href="'+feeds.link+'" title="'+ feeds.description +'">'+ feeds.title +'</a>' +
                '</div>';
         
        // Add body
        html += '<div class="rssBody">' +
            '<ul>';
     
        // Add feeds
        for (var i=0; i<feeds.entries.length; i++) {
         
            // Get individual feed
            var entry = feeds.entries[i];
            var pubDate;
 
            // Format published date
            if (entry.publishedDate) {
                var entryDate = new Date(entry.publishedDate);
                var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
            }
         
            // Add feed row
            html += '<li class="rssRow '+row+'">' +
                '<'+ options.titletag +'><a href="'+ entry.link +'" title="View this feed at '+ feeds.title +'">'+ entry.title +'</a></'+ options.titletag +'>'
            if (options.date && pubDate) html += '<div>'+ pubDate +'</div>'
            if (options.content) {
         
                // Use feed snippet if available and optioned
                if (options.snippet && entry.contentSnippet != '') {
                    var content = entry.contentSnippet;
                } else {
                    var content = entry.content;
                }
             
                html += '<p>'+ content +'</p>'
            }
         
            // Add any media
            if (options.media && xmlEntries.length > 0) {
                var xmlMedia = xmlEntries[i].getElementsByTagName('enclosure');
                if (xmlMedia.length > 0) {
                    html += '<div class="rssMedia"><div>Media files</div><ul>'
                    for (var m=0; m<xmlMedia.length; m++) {
                        var xmlUrl = xmlMedia[m].getAttribute("url");
                        var xmlType = xmlMedia[m].getAttribute("type");
                        var xmlSize = xmlMedia[m].getAttribute("length");
                        html += '<li><a href="'+ xmlUrl +'" title="Download this media">'+ xmlUrl.split('/').pop() +'</a> ('+ xmlType +', '+ formatFilesize(xmlSize) +')</li>';
                    }
                    html += '</ul></div>'
                }
                html += '</li>';
            }
         
            // Alternate row classes
            if (row == 'odd') {
                row = 'even';
            } else {
                row = 'odd';
            }        
        }
     
        html += '</ul>' +
            '</div>'
     
        $(e).html(html);
 
        // Apply target to links
        $('a',e).attr('target',options.linktarget);
    };
 
    function formatFilesize(bytes) {
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
        var e = Math.floor(Math.log(bytes)/Math.log(1024));
        return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
    }
 
    function getXMLDocument(string) {
        var browser = navigator.appName;
        var xml;
        if (browser == 'Microsoft Internet Explorer') {
            xml = new ActiveXObject('Microsoft.XMLDOM');
            xml.async = 'false'
            xml.loadXML(string);
        } else {
            xml = (new DOMParser()).parseFromString(string, 'text/xml');
        }
        return xml;
    }
 
})(jQuery);
 
 
TSC_VTICKER.JS
 
/*
* Tadas Juozapaitis ( kasp3rito@gmail.com )
* Modifed by Zazar:
* 24.06.2011 - Corrected pausing issue with multiple instances
*
*/
 
(function($){
 
$.fn.vTicker = function(options) {
    var defaults = {
        speed: 300,
        pause: 6000,
        showItems: 3,
        animation: '',
        mousePause: true,
        isPaused: false
    };
 
    var options = $.extend(defaults, options);
 
    moveUp = function(obj2, height, paused){
        if(paused) return;
     
        var obj = obj2.children('ul');
     
            first = obj.children('li:first').clone(true);
     
            obj.animate({top: '-=' + height + 'px'}, options.speed, function() {
                $(this).children('li:first').remove();
                $(this).css('top', '0px');
            });
     
        if(options.animation == 'fade') {
            obj.children('li:first').fadeOut(options.speed);
            obj.children('li:last').hide().fadeIn(options.speed);
        }
 
            first.appendTo(obj);
    };
 
    return this.each(function() {
        var obj = $(this);
        var maxHeight = 0;
        var itempause = options.isPaused;
 
        obj.css({overflow: 'hidden', position: 'relative'})
            .children('ul').css({position: 'absolute', margin: 0, padding: 0})
            .children('li').css({margin: 0, padding: 0});
 
        obj.children('ul').children('li').each(function(){
 
            if($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
 
        obj.children('ul').children('li').each(function() {
            $(this).height(maxHeight);
        });
 
        obj.height(maxHeight * options.showItems);
     
            var interval = setInterval(function(){ moveUp(obj, maxHeight, itempause); }, options.pause);
     
        if (options.mousePause)
        {
            obj.bind("mouseenter",function() {
                itempause = true;
            }).bind("mouseleave",function() {
                itempause = false;
            });
        }
    });
};
})(jQuery);
 
 
SOURCE CODE INSERTED INTO PAGE WHERE TICKER TO APPEAR
(Medical News Today RSS Feed inserted as an example)
 
<head>
<!-- DC RSS Feeds JS -->
<script src="tsc_rssfeed.js"></script>
<script src="tsc_vticker.js"></script>
</head>
 
<body>
<body>
<!-- DC RSS Feeds Start -->
<div id="rss-ticker1" style="width:80%;"></div>
<!-- DC RSS Feeds End -->
<!--
Parameters:
rssfeed ('enter-rss-url-here')
showItems: x - Specify number of news items to show
for more settings, edit tsc_vticker.js
-->
</div>
</div>
 
<div class="rss-container"><div class="rss-icon"><img src="../img/icons/rss-shadow.jpg" alt="rss icon"></div>
<div class="rss-feed">
<!-- Medical News Today - Complementary Medicine - DC RSS Feeds Settings -->
<script>
$(document).ready(function () {
    $('#rss-ticker2').rssfeed('http://www.medicalnewstoday.com/rss/complementary_medicine.xml',{}, function(e) {
        $(e).find('div.rssBody').vTicker({ showItems: 1});
    });
});
</script>
</body>
 
 
(source code posted is copyright of its respective owners)

 

 

Edited by aitch

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

×