December 16, 2012
Display random labels on blogspot blog
This Javascript snippet will retrieve random labels from a blogspot blog and display it in sidebar or anywhere else, useful if you've too many labels and only want show 'x' number of random labels on each page load.Technology used:
Javascript, YQL, JSON feed
Usage:
- Configure and include the snippet and add label div to blog template/html.
View/Copy snippet:
- /**
- * @author Manish Raj
- * @website http://www.technoslab.in
- */
- // Configure
- var blog_url = 'www.technoslab.in'; // Just the host. Example. yourblog.blogspot.com
- var max_labels = 50; // Maximum number of random labels to show.
- var label_element = 'labels'; // id of the element where labels would be displayed. Example: <div id="labels"></div>
- function showLabels(){
- var queryUrl = 'http://query.yahooapis.com/v1/public/yql?q=select%20feed.category%20from%20json%20where%20url%3D%22http%3A%2F%2F' + blog_url + '%2Ffeeds%2Fposts%2Fsummary%3Falt%3Djson%26max-results%3D0%22&format=json&callback=labelCb'
- var script = document.createElement('script');
- script.setAttribute('type', 'text/javascript');
- script.setAttribute('src', queryUrl);
- document.getElementsByTagName('body')[0].appendChild(script);
- }
- // Label Callback
- function labelCb(response){
- var html = '';
- if(response.query.count > 0){
- response.query.results.json = response.query.results.json.shuffle();
- for(var i = 0; i < response.query.count && i < max_labels; i++){
- html += '<a href="http://'+blog_url+'/search/label/'+response.query.results.json[i].feed.category.term+'">'+response.query.results.json[i].feed.category.term+'</a>, ';
- }
- }
- document.getElementById(label_element).innerHTML = html;
- }
- // From SO: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
- Array.prototype.shuffle = function () {
- for (var i = this.length - 1; i > 0; i--) {
- var j = Math.floor(Math.random() * (i + 1));
- var tmp = this[i];
- this[i] = this[j];
- this[j] = tmp;
- }
- return this;
- }
- // Load and show labels
- window.onload = function(){
- showLabels();
- }
Or Download: http://pastebin.com/raw.php?i=PkZY87yV
Related Posts
Subscribe to:
Post Comments (Atom)
Sweet blog! I found it while searching on Yahoo
ReplyDeleteΝews. Do you have any suggestions on how to get listеd in Yahoo Νeωs?
I've been trying for a while but I never seem to get there! Many thanks
Look into my web page ; v2 cigs
This is totally uncool man. Did I ever spam on your website?
Delete