Need to generate an JSON Array for HTML Elements in Javascript - javascript

Use case 1:
<sub><b><i>boldSubscriptContent</i></b></sub>
Output JSON:
[{
"subscript": true,
"content": "boldSubscriptContent",
"bold": true
}]
Use case 2:
withoutAnyHTML<b>boldContent<sub>boldSubscriptContent</sub></b>
Output JSON :
[{
"content": "WithoutAnyHTML"
}, {
"bold": true,
"content": "boldContent"
}, {
"bold": true,
"subscript": true,
"content": "boldSubscriptContent",
"outerHTML": "<sub>subscriptContent</sub>"
}]
Use case 3:
<b><i>ItalicContent</i><sub>subscriptContent</sub><sup>supscriptContent</sup></b>
Output JSON:
[{
"italic": true,
"bold": true,
"content": "ItalicContent",
"outerHTML": "<i>ItalicContent</i>"
}, {
"subscript": true,
"bold": true,
"content": "subscriptContent",
"outerHTML": "<sub>subscriptContent</sub>"
}, {
"superscript": true,
"bold": true,
"content": "supscriptContent",
"outerHTML": "<sup>supscriptContent</sup>"
}]

Here is the solution:
JSFiddle working link
<html>
<head>
<script src = "https://code.jquery.com/jquery-3.2.1.min.js"> </script>
<script>
var res = [];
function parseText(cont, det) {
det = JSON.parse(JSON.stringify(det));
if (cont.tagName === 'B')
det.b = true;
if (cont.tagName === 'I')
det.i = true;
if (cont.tagName === 'U')
det.u = true;
if (cont.tagName === 'SUB')
det.sub = true;
if (cont.tagName === 'SUP')
det.sup = true;
if (cont.tagName) {
for (var i = 0; i < cont.childNodes.length; i++) {
var child = cont.childNodes[i];
if (child.tagName) {
parseText(child, det);
} else {
res.push({
det,
content: child.data
});
}
}
} else {
res.push({
det,
content: cont.data
});
}
}
function calculate(){
var str = document.getElementById('str').value;
var cont = $('<div></div>').html(str);
for (var i = 0; i < cont.length; i++) {
parseText(cont[i], {
i: false,
b: false,
u: false,
sub: false,
sup: false
});
}
var resHTML = '';
for (var i = 0; i < res.length; i++) {
resHTML += res[i].content + "\t:" + JSON.stringify(res[i].det) + "</br>";
}
document.getElementById('output').innerHTML = resHTML;
}
</script>
</head>
<body>
<input type="text" id="str" value="<b>content<sup>superTest</sup><sub>subTest</sub><i>testItalic</i></b>" />
<button onclick="calculate()">Parse</button>
<div id = "output"></label>
</body>
</html>

Related

Multiple filters work together. Match multiple filter types together

I have several different filter types.The type of filters is checkbox and rang-price and select-option.Each of these filters works individually.But I want group filters to work.please help my.
let FlyList = [{
"id": "1",
"flight_number": "961",
"type_ticket": "systemi",
"airline": "ata",
"fly_time": "04:00",
"class_type": "economy",
"price": "10000",
"capacity": "2",
}, {
"id": "2",
"flight_number": "960",
"type_ticket": "chartery",
"airline": "Air-Tour",
"fly_time": "08:00",
"class_type": "Business",
"price": "20000",
"capacity": "3",
}, {
"id": "3",
"flight_number": "950",
"type_ticket": "systemi",
"airline": "taban",
"fly_time": "11:00",
"class_type": "Business",
"price": "30000",
"capacity": "5",
},
];
let filters = new Array();
function rangeSlider() {
$(".range-slider").ionRangeSlider({
hide_min_max: true,
keyboard: true,
min: 0,
max: 150,
from: 0,
to: 140,
type: 'double',
step: 1,
prefix: "$",
grid: true,
onFinish: function(data) {
var _price = filters.findIndex(item => item.field === 'price');
if (_price != -1) filters[_price]['value'] = [data.from, data.to];
else addOrRemoveFilter('price', [data.from, data.to], true);
customFilter();
// console.log(addOrRemoveFilter('price', [data.from, data.to], true));
}
});
}
function customFilter() {
let filtered_list = [];
FlyList.filter(item => {
filters.forEach(function(el, i) {
let _field = el['field'];
let _value = el['value'];
// console.log(_value);
if (typeof(_value) === 'object' && _value.length) {
if(parseInt(item[_field]) >= (parseInt(_value[0] * 1000)) && parseInt(item[_field]) <= (parseInt(_value[1]*1000))){
filtered_list.push(item);
}
else{
FlyList = [];
}
} else {
let isMulti = _value.split(',');
//RANGE PRICE SLIDER
if (isMulti.length > 1) {
let time = miliseconds(item[_field].split(':')[0], item[_field].split(':')[1])
let num1 = miliseconds(isMulti[0].split(':')[0], isMulti[0].split(':')[1]);
let num2 = miliseconds(isMulti[1].split(':')[0], isMulti[1].split(':')[1]);
if (time >= num1 && time <= num2) filtered_list.push(item);
} else {
//end RANGE PRICE SLIDER
item[_field] == _value ? filtered_list.push(item) : false;
}
}
})
});
function miliseconds(hrs,min) {
return((hrs*60*60+min*60)*1000);
}
$('#flights').updateDom(filtered_list.length ? filtered_list : FlyList, {
animate: true,
});
}
let filterCheckboxes = document.querySelectorAll('.filtersAll');
filterCheckboxes.forEach(checkbox => checkbox.addEventListener('change', (e) => {
e.preventDefault();
let filterTypeElement = findFilterTypeElement(e.target);
if (filterTypeElement) {
let field = filterTypeElement.getAttribute('data-field');
let val = e.target.value;
addOrRemoveFilter(field,val,e.target.checked);
customFilter();
}
}));
document.getElementById('optionAll').addEventListener('change' ,(e)=>{
e.preventDefault();
let filterTypeElement = findFilterTypeElement(e.target);
if (filterTypeElement) {
let field = filterTypeElement.getAttribute('data-field');
let val = e.target.value;
addOrRemoveFilter(field,val,true);
for(var index = 0 ; index < e.target.options.length ; index++)
{
addOrRemoveFilter(field,e.target.options[index].value,false);
}
addOrRemoveFilter(field,val,true);
customFilter();
}
})
function addOrRemoveFilter(f,v,add) {
if(add) {
filters.push({field : f.toLowerCase() , value : v});
} else {
for(let i = 0;i < filters.length ; i++) {
if(filters[i].field === f.toLowerCase() && filters[i].value === v) {
filters.splice(i,1);
}
}
}
// console.log(filters);
}
function getParents(el, parentSelector /* optional */) {
// If no parentSelector defined will bubble up all the way to *document*
if (parentSelector === undefined) {
parentSelector = document;
}
var parents = [];
var p = el.parentNode;
while (p && (p !== parentSelector || p.parentNode)) {
var o = p;
parents.push(o);
p = o.parentNode;
}
parents.push(parentSelector); // Push that parentSelector you wanted to stop at
return parents;
}
function findFilterTypeElement(el) {
var result = null;
var parents = getParents(el);
parents.forEach((item) => {
if (hasClass(item, 'filter_type') && result == null) {
result = item;
}
});
return result;
}
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}

get quaggaJS barcode results on input field

I am a newbie to HTML/Javascript Language.
I am trying to implement quaggaJS barcode scanner Using the live-stream into my HTML page. its working fine but what i want is to get the result on input field.
Below is my input field:
<input class="form-control" type="number" name="id" required autofocus>
This is live_w_locator.js file from quaggaJS:
$(function() {
var resultCollector = Quagga.ResultCollector.create({
capture: true,
capacity: 20,
blacklist: [{
code: "WIWV8ETQZ1", format: "code_93"
}, {
code: "EH3C-%GU23RK3", format: "code_93"
}, {
code: "O308SIHQOXN5SA/PJ", format: "code_93"
}, {
code: "DG7Q$TV8JQ/EN", format: "code_93"
}, {
code: "VOFD1DB5A.1F6QU", format: "code_93"
}, {
code: "4SO64P4X8 U4YUU1T-", format: "code_93"
}],
filter: function(codeResult) {
// only store results which match this constraint
// e.g.: codeResult
return true;
}
});
var App = {
init: function() {
var self = this;
Quagga.init(this.state, function(err) {
if (err) {
return self.handleError(err);
}
//Quagga.registerResultCollector(resultCollector);
App.attachListeners();
App.checkCapabilities();
Quagga.start();
});
},
handleError: function(err) {
console.log(err);
},
checkCapabilities: function() {
var track = Quagga.CameraAccess.getActiveTrack();
var capabilities = {};
if (typeof track.getCapabilities === 'function') {
capabilities = track.getCapabilities();
}
this.applySettingsVisibility('zoom', capabilities.zoom);
this.applySettingsVisibility('torch', capabilities.torch);
},
updateOptionsForMediaRange: function(node, range) {
console.log('updateOptionsForMediaRange', node, range);
var NUM_STEPS = 6;
var stepSize = (range.max - range.min) / NUM_STEPS;
var option;
var value;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0; i <= NUM_STEPS; i++) {
value = range.min + (stepSize * i);
option = document.createElement('option');
option.value = value;
option.innerHTML = value;
node.appendChild(option);
}
},
applySettingsVisibility: function(setting, capability) {
// depending on type of capability
if (typeof capability === 'boolean') {
var node = document.querySelector('input[name="settings_' + setting + '"]');
if (node) {
node.parentNode.style.display = capability ? 'block' : 'none';
}
return;
}
if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
var node = document.querySelector('select[name="settings_' + setting + '"]');
if (node) {
this.updateOptionsForMediaRange(node, capability);
node.parentNode.style.display = 'block';
}
return;
}
},
initCameraSelection: function(){
var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();
return Quagga.CameraAccess.enumerateVideoDevices()
.then(function(devices) {
function pruneText(text) {
return text.length > 30 ? text.substr(0, 30) : text;
}
var $deviceSelection = document.getElementById("deviceSelection");
while ($deviceSelection.firstChild) {
$deviceSelection.removeChild($deviceSelection.firstChild);
}
devices.forEach(function(device) {
var $option = document.createElement("option");
$option.value = device.deviceId || device.id;
$option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
$option.selected = streamLabel === device.label;
$deviceSelection.appendChild($option);
});
});
},
attachListeners: function() {
var self = this;
self.initCameraSelection();
$(".controls").on("click", "button.stop", function(e) {
e.preventDefault();
Quagga.stop();
self._printCollectedResults();
});
$(".controls .reader-config-group").on("change", "input, select", function(e) {
e.preventDefault();
var $target = $(e.target),
value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
name = $target.attr("name"),
state = self._convertNameToState(name);
console.log("Value of "+ state + " changed to " + value);
self.setState(state, value);
});
},
_printCollectedResults: function() {
var results = resultCollector.getResults(),
$ul = $("#result_strip ul.collector");
results.forEach(function(result) {
var $li = $('<li><div class="thumbnail"><div class="imgWrapper"><img /></div><div class="caption"><h4 class="code"></h4></div></div></li>');
$li.find("img").attr("src", result.frame);
$li.find("h4.code").html(result.codeResult.code + " (" + result.codeResult.format + ")");
$ul.prepend($li);
});
},
_accessByPath: function(obj, path, val) {
var parts = path.split('.'),
depth = parts.length,
setter = (typeof val !== "undefined") ? true : false;
return parts.reduce(function(o, key, i) {
if (setter && (i + 1) === depth) {
if (typeof o[key] === "object" && typeof val === "object") {
Object.assign(o[key], val);
} else {
o[key] = val;
}
}
return key in o ? o[key] : {};
}, obj);
},
_convertNameToState: function(name) {
return name.replace("_", ".").split("-").reduce(function(result, value) {
return result + value.charAt(0).toUpperCase() + value.substring(1);
});
},
detachListeners: function() {
$(".controls").off("click", "button.stop");
$(".controls .reader-config-group").off("change", "input, select");
},
applySetting: function(setting, value) {
var track = Quagga.CameraAccess.getActiveTrack();
if (track && typeof track.getCapabilities === 'function') {
switch (setting) {
case 'zoom':
return track.applyConstraints({advanced: [{zoom: parseFloat(value)}]});
case 'torch':
return track.applyConstraints({advanced: [{torch: !!value}]});
}
}
},
setState: function(path, value) {
var self = this;
if (typeof self._accessByPath(self.inputMapper, path) === "function") {
value = self._accessByPath(self.inputMapper, path)(value);
}
if (path.startsWith('settings.')) {
var setting = path.substring(9);
return self.applySetting(setting, value);
}
self._accessByPath(self.state, path, value);
console.log(JSON.stringify(self.state));
App.detachListeners();
Quagga.stop();
App.init();
},
inputMapper: {
inputStream: {
constraints: function(value){
if (/^(\d+)x(\d+)$/.test(value)) {
var values = value.split('x');
return {
width: {min: parseInt(values[0])},
height: {min: parseInt(values[1])}
};
}
return {
deviceId: value
};
}
},
numOfWorkers: function(value) {
return parseInt(value);
},
decoder: {
readers: function(value) {
if (value === 'ean_extended') {
return [{
format: "ean_reader",
config: {
supplements: [
'ean_5_reader', 'ean_2_reader'
]
}
}];
}
return [{
format: value + "_reader",
config: {}
}];
}
}
},
state: {
inputStream: {
type : "LiveStream",
constraints: {
width: {min: 640},
height: {min: 480},
facingMode: "environment",
aspectRatio: {min: 1, max: 2}
}
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: 2,
frequency: 10,
decoder: {
readers : [{
format: "code_128_reader",
config: {}
}]
},
locate: true
},
lastResult : null
};
App.init();
Quagga.onProcessed(function(result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 2});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "#00F", lineWidth: 2});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: 'red', lineWidth: 3});
}
}
});
Quagga.onDetected(function(result) {
var code = result.codeResult.code;
if (App.lastResult !== code) {
App.lastResult = code;
var $node = null, canvas = Quagga.canvas.dom.image;
$node = $('<li><div class="thumbnail"><div class="imgWrapper"><img /></div><div class="caption"><h4 class="code"></h4></div></div></li>');
$node.find("img").attr("src", canvas.toDataURL());
$node.find("h4.code").html(code);
$("#result_strip ul.thumbnails").prepend($node);
}
});
});
Appreciate your help...Thank You
You can get the reference of your input control and set its value to the code variable in the onDetected code block.
Quagga.onDetected(function(result) {
var code = result.codeResult.code;
document.getElementById('MyInput').value = code;
});

Dijit Selects, Items in the Combobox disabled = true doesn't works

This is my code and it doesn't works. It belong to a combobox. Some items should be disabled in it.
var data = [];
for (i = 0; i < items.length; i++) {
data.push({id: items[i].id, label: "foobaa"});
data.getOptions(items[i].id).disabled = true;
}
var memory = new Memory({
idProperty: "id",
data: data
});
this._widget.set("store", memory);
I found a code snipe at fiddle.net and this works but im not able to converte it to my problem.
http://jsfiddle.net/g00glen00b/akcZy/
Also the otherwise super documentation of dojo doesn't helps me :-(
http://dojotoolkit.org/documentation/tutorials/1.10/selects_using_stores/
I have made some changes try this and let me know is this your need? Use the code below to disable all the select items.
var data = [];
for (i = 0; i < myData.length; i++) {
data.push('{id: myData[i].id, label: "foobaa"}');
registry.byId("mySelect").getOptions(myData[i].id).disabled = true;
}
http://jsfiddle.net/f3snxrrd/
http://jsfiddle.net/5pgkkf0z/
items: {
mutators: {
value: [],
type: verify.ARRAY
},
widget: {
updateI18n: true,
mapping: function (widget, items) {
if (this._widget) {
var i;
var data = [];
for (i = 0; i < items.length; i++) {
data.push({id: items[i].id, label: i18n.resolveSequence(items[i].label)});
//register.byId(data).getOptions((items[i].value).disabled = true);
}
var memory = new Memory({
idProperty: "id",
data: data
});
this._widget.set("store", memory);
this._widget.closeDropDown(true);
this._widget.reset();
if (items.length === 0) {
this._enabledItems = false;
}
else if (items.length === 1) {
this.set("selectedId", items[0].id);
this._enabledItems = (this.get("selectedId") !== items[0].id);
}
else {
this._enabledItems = true;
}
this._widget.set("disabled", !(this._enabledState && this._enabledItems ));
}
}
}
},
_createWidget: function () {
var ret;
ret = new Select({id: this.uniqueId, disabled: true, labelAttr: "label", labelType: "Text", required: false, store: new Memory({data: []})});
var that = this;
ret.own(on(ret, "change", function (value) {that._onChange(value); }));
return ret;
},
This is the items array:
The code from jsfiddle.net
http://jsfiddle.net/8m52n81u/11/
I can't change the items array :-/
items = [{
id: "0",
label: key[{0: "foo", 1: "baa"}]
}, {
id: "1",
label: key[{0: "foo", 1: "baa"}]
}];
require([
"dojo/ready",
"dijit/registry",
"dijit/form/Select",
"dojo/store/Memory",
"dojo/parser"
], function(ready, registry) {
ready(function() {
var data = [];
for (i = 0; i < items.length; i++) {
data.push('{id: items[i].id, label: items[i].label}');
registry.byId("uniqueId").getOptions(items[i].id).disabled = true;
}
});
});

How can I resize Jira gadgets' data?

I am implementing a Jira gadget. I have an problem about retrieve data.
I am retrieving data from DB to gadget. There are lots of columns so the gadget cannot show all columns. I guess I have to resize data. There is one more thing; how can I stop the retrieving data to go end of pages?
Here is my gadget.xml
#requireResource("com.atlassian.gadgets.publisher:ajs-gadgets")
#requireResource("sqlGadget:Web-resources")
#requireResource("com.atlassian.jira.gadgets:common")
#requireResource("com.atlassian.jira.gadgets:autocomplete")
#includeResources()
<script type="text/javascript">
(function () {
var gadget = AJS.Gadget({
baseUrl: "__ATLASSIAN_BASE_URL__",
useOauth: "/rest/gadget/1.0/currentUser",
config: {
descriptor: function(args) {
var gadget = this;
gadgets.window.setTitle("SQL Gadget Config");
var projectPicker = AJS.gadget.fields.projectPicker(gadget, "projectId", args.projectOptions);
return {
fields: [
projectPicker,
{
id: "configNumber-id",
userpref: "configNumber",
label: "Config number",
description: "",
type: "select",
selected: gadget.getPref("configNumber"),
options: [
{
label:"1",
value:"1"
},
{
label:"2",
value:"2"
},
{
label:"3",
value:"3"
}
]
},
AJS.gadget.fields.nowConfigured()
]
};
},
args: function()
{
return [
{
key: "projectOptions",
ajaxOptions: "/rest/gadget/1.0/filtersAndProjects?showFilters=false"
}
];
}()
},
view: {
/* HTML PART*/
onResizeAdjustHeight: true,
enableReload: true,
template: function (args)
{
var gadget = this;
var response = args.projects.value;
AJS.$.each(AJS.$.parseJSON(response), function(idx, obj) {
console.log(obj);
});
var myList=AJS.$.parseJSON(response);
var test="<body onLoad=buildHtmlTable()><table id=excelDataTable border=1> </table></body>";
document.getElementById("myDiv").innerHTML = test;
var columns = addAllColumnHeaders(myList);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = AJS.$('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append(AJS.$('<td/>').html(cellValue));
}
AJS.$("#excelDataTable").append(row$);
}
function addAllColumnHeaders(myList)
{
var columnSet = [];
var headerTr$ = AJS.$('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if (AJS.$.inArray(key, columnSet) == -1){
columnSet.push(key);
headerTr$.append(AJS.$('<th/>').html(key));
}
}
}
AJS.$("#excelDataTable").append(headerTr$);
return columnSet;
}
},
args: [
{
key: "projects",
ajaxOptions: function ()
{
var projectName;
var confOrder;
var projectField = document.getElementById("projectId");
var confNumbElement = document.getElementById("configNumber-id");
if(projectField != null){
projectName = projectField.options[projectField.selectedIndex].text;
console.log(projectName);
}
if(confNumbElement != null){
confOrder = confNumbElement.options[confNumbElement.selectedIndex].text;
console.log(confOrder);
this.configNumber = confOrder;
}
return {
url: "/rest/sqlrestsource/latest/execute",
data: {
projectId : gadgets.util.unescapeString(this.getPref("projectId")),
configNumber : gadgets.util.unescapeString(this.getPref("configNumber")),
}
};
}
}
]
}
});
})();

How do I display my RSS feed horizontally?

I want to display my custom RSS feed as a horizontal list. I am using a responsive template and embedding my feeds into that template. I believe that my JavaScript is not separating each RSS post into a separate list item like I thought it would.
(function($) {
"use strict";
var RSS = function(target, url, options, callback) {
this.target = target
this.url = url
this.html = []
this.effectQueue = []
this.options = $.extend({
ssl: false,
limit: null,
key: null,
layoutTemplate: '<ul style="display:inline-block;">{entries}</ul>',
entryTemplate: '<li><div class="title">{title}</div><br /><author>{author}</author><img src="{teaserImageUrl}"></img><date>{date}</date><br />{shortBodyPlain}</li>',
tokens: {
},
outputMode: 'json',
dateFormat: 'MMM Do, YYYY',
effect: 'show',
offsetStart: false,
offsetEnd: false,
error: function() {
console.log("jQuery RSS: url doesn't link to RSS-Feed");
},
onData: function(){},
success: function(){}
}, options || {})
this.callback = callback || this.options.success
}
RSS.htmlTags = ["doctype", "html", "head", "title", "base", "link", "meta", "style", "script", "noscript", "body", "article", "nav", "aside", "section", "header", "footer", "h1-h6", "hgroup", "address", "p", "hr", "pre", "blockquote", "ol", "ul", "li", "dl", "dt", "dd", "figure", "figcaption", "div", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", "col", "colgroup", "form", "fieldset", "legend", "label", "input", "button", "select", "datalist", "optgroup", "option", "textarea", "keygen", "output", "progress", "meter", "details", "summary", "command", "menu", "del", "ins", "img", "iframe", "embed", "object", "param", "video", "audio", "source", "canvas", "track", "map", "area", "a", "em", "strong", "i", "b", "u", "s", "small", "abbr", "q", "cite", "dfn", "sub", "sup", "time", "code", "kbd", "samp", "var", "mark", "bdi", "bdo", "ruby", "rt", "rp", "span", "br", "wbr"]
RSS.prototype.load = function(callback) {
var apiProtocol = "http" + (this.options.ssl ? "s" : "")
, apiHost = apiProtocol + "://ajax.googleapis.com/ajax/services/feed/load"
, apiUrl = apiHost + "?v=1.0&output=" + this.options.outputMode + "&callback=?&q=" + encodeURIComponent(this.url)
// set limit to offsetEnd if offset has been set
if(this.options.offsetStart && this.options.offsetEnd) this.options.limit = this.options.offsetEnd;
if (this.options.limit != null) apiUrl += "&num=" + this.options.limit;
if (this.options.key != null) apiUrl += "&key=" + this.options.key;
$.getJSON(apiUrl, callback)
}
RSS.prototype.render = function() {
var self = this
this.load(function(data) {
try {
self.feed = data.responseData.feed
self.entries = data.responseData.feed.entries
} catch(e) {
self.entries = []
self.feed = null
return self.options.error.call(self)
}
var html = self.generateHTMLForEntries()
self.target.append(html.layout)
if (html.entries.length !== 0) {
$.isFunction(self.options.onData) && self.options.onData.call(self);
self.appendEntriesAndApplyEffects($("entries", html.layout), html.entries);
}
if (self.effectQueue.length > 0) {
self.executeEffectQueue(self.callback)
} else {
$.isFunction(self.callback) && self.callback.call(self);
}
})
}
RSS.prototype.appendEntriesAndApplyEffects = function(target, entries) {
var self = this
$.each(entries, function(idx, entry) {
var $html = self.wrapContent(entry)
if(self.options.effect === 'show') {
target.before($html)
} else {
$html.css({ display: 'none' })
target.before($html)
self.applyEffect($html, self.options.effect)
}
})
target.remove()
}
RSS.prototype.generateHTMLForEntries = function() {
var self = this
, result = {
entries: [],
layout: null
}
$(this.entries).each(function() {
var entry = this,
offsetStart = self.options.offsetStart,
offsetEnd = self.options.offsetEnd;
// offset required
if(offsetStart && offsetEnd) {
if(index >= offsetStart && index <= offsetEnd) {
if(self.isRelevant(entry, result.entries)) {
var evaluatedString = self.evaluateStringForEntry(self.options.entryTemplate, entry)
result.entries.push(evaluatedString)
}
}
}else{
// no offset
if(self.isRelevant(entry, result.entries)) {
var evaluatedString = self.evaluateStringForEntry(self.options.entryTemplate, entry)
result.entries.push(evaluatedString)
}
}
})
if(!!this.options.entryTemplate) {
// we have an entryTemplate
result.layout = this.wrapContent(this.options.layoutTemplate.replace("{entries}", "<entries></entries>"))
} else {
// no entryTemplate available
result.layout = this.wrapContent("<div><entries></entries></div>")
}
return result
}
RSS.prototype.wrapContent = function(content) {
if($.trim(content).indexOf('<') !== 0) {
// the content has no html => create a surrounding div
return $("<div>" + content + "</div>")
} else {
// the content has html => don't touch it
return $(content)
}
}
RSS.prototype.applyEffect = function($element, effect, callback) {
var self = this
switch(effect) {
case 'slide':
$element.slideDown('slow', callback)
break
case 'slideFast':
$element.slideDown(callback)
break
case 'slideSynced':
self.effectQueue.push({ element: $element, effect: 'slide' })
break
case 'slideFastSynced':
self.effectQueue.push({ element: $element, effect: 'slideFast' })
break
}
}
RSS.prototype.executeEffectQueue = function(callback) {
var self = this
this.effectQueue.reverse()
var executeEffectQueueItem = function() {
var item = self.effectQueue.pop()
if(item) {
self.applyEffect(item.element, item.effect, executeEffectQueueItem)
} else {
callback && callback()
}
}
executeEffectQueueItem()
}
RSS.prototype.evaluateStringForEntry = function(string, entry) {
var result = string
, self = this
$(string.match(/(\{.*?\})/g)).each(function() {
var token = this.toString()
result = result.replace(token, self.getValueForToken(token, entry))
})
return result
}
RSS.prototype.isRelevant = function(entry, entries) {
var tokenMap = this.getTokenMap(entry)
if(this.options.filter) {
if(this.options.filterLimit && (this.options.filterLimit == entries.length)) {
return false
} else {
return this.options.filter(entry, tokenMap)
}
} else {
return true
}
}
RSS.prototype.getTokenMap = function(entry) {
if (!this.feedTokens) {
var feed = JSON.parse(JSON.stringify(this.feed))
delete feed.entries
this.feedTokens = feed
}
return $.extend({
feed: this.feedTokens,
url: entry.link,
author: entry.author,
date: moment(entry.publishedDate).format(this.options.dateFormat),
title: entry.title,
body: entry.content,
shortBody: entry.contentSnippet,
bodyPlain: (function(entry) {
var result = entry.content
.replace(/<script[\\r\\\s\S]*<\/script>/mgi, '')
.replace(/<\/?[^>]+>/gi, '')
for(var i = 0; i < RSS.htmlTags.length; i++) {
result = result.replace(new RegExp('<' + RSS.htmlTags[i], 'gi'), '')
}
return result
})(entry),
shortBodyPlain: entry.contentSnippet.replace(/<\/?[^>]+>/gi, ''),
//shortBodyPlain: entry.contentSnippet.replace("-- Delivered by Feed43 service", ""),
shortBodyPlain: entry.contentSnippet.replace("369gopee", "<author>").replace("321gopee", "</author><br />"),
index: $.inArray(entry, this.entries),
totalEntries: this.entries.length,
teaserImage: (function(entry){
try { return entry.content.match(/(<img.*?>)/gi)[0] }
catch(e) { return "" }
})(entry),
teaserImageUrl: (function(entry) {
try { return entry.content.match(/(<img.*?>)/gi)[0].match(/src="(.*?)"/)[1] }
catch(e) { return "" }
})(entry)
}, this.options.tokens)
}
RSS.prototype.getValueForToken = function(_token, entry) {
var tokenMap = this.getTokenMap(entry)
, token = _token.replace(/[\{\}]/g, '')
, result = tokenMap[token]
if(typeof result != 'undefined')
return ((typeof result == 'function') ? result(entry, tokenMap) : result)
else
throw new Error('Unknown token: ' + _token)
}
$.fn.rss = function(url, options, callback) {
new RSS(this, url, options, callback).render()
return this; //implement chaining
}
})(jQuery)
When I view the page source, there is not dynamically created html. How would I display these list items inline?
The feeds appear in HTML as follows:
<script>
jQuery(function($) {
$("#rss-feeds").rss("http://www.feed43.com/channelfireball.xml", {
limit: 15
})
</script>
<div style="border:none;width:100%;height:auto;overflow-y:scroll;
overflow-x:scroll;">
<div class="span2 item">
<div class="item-wrap">
<div class="post_results" id="rss-feeds"></div>
</div>
</div>
</div>

Categories

Resources