Using JavaScript / jQuery to "pause" execution and wait for user input - javascript

I am trying to use JavaScript & jQuery to overwrite standard functionality - namely alert and confirm.
For this, I have built something that shows a dialog when an alert or confirm is asked for by the code, and this looks like:
function throwError(e_content) {
var e_title = "Error";
var e = errordiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return;
}
function throwConfirm(e_content) {
function confirmCallback() {
var retval = "213";
jQuery("body").on("click", function (e) {
if (e.target.id == "confirm_okay") {
hideError();
retval = true;
}
else if (e.target.id == "confirm_cancel") {
hideError();
retval = false;
}
})
retval == "213" ? confirmCallback() : retval;
return retval;
}
var e_title = "Confirm Action";
var e = confirmdiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return confirmCallback();
}
function hideError () {
jQuery(document).find(".custom_error_div").remove();
return;
}
var errordiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="alert_okay">Ok</button>'
+ '</div>'
};
var confirmdiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="confirm_okay">Ok</button><button id="confirm_cancel">Cancel</button>'
+ '</div>'
};
The basis of this is working, it alerts and confirms when I want it to - but the confirm is an issue, when clicking either "Yes" or "No", the throwConfirm function is supposed to return true or false and this doesn't seem to be happening, instead, I reach maximum call size.
The basis behind doing this are complex and convoluted and not relevant to the question at hand - what I need to know is:
How do I get the throwConfirm function to return true or false based on what button the user clicks?

This shows one way of doing it. It's kind of kludgy - there's going to be a better way of setting the callback instead of using the global _callback variable
"use strict";
function throwError(e_content) {
var e_title = "Error";
var e = errordiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return;
}
function throwConfirm(e_content, callback) {
hideError();
var e_title = "Confirm Action";
var e = confirmdiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
// this is a hack, but I'm tired
_callback = callback
}
function hideError () {
jQuery(document).find(".custom_error_div").remove();
return;
}
var errordiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="alert_okay">Ok</button>'
+ '</div>'
};
var confirmdiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="confirm_okay">Ok</button><button id="confirm_cancel">Cancel</button>'
+ '</div>'
};
var _callback;
function init() {
jQuery("body").on("click", function (e) {
if (e.target.id == "confirm_okay") {
hideError();
_callback( true );
}
else if (e.target.id == "confirm_cancel") {
hideError();
_callback( false );
}
})
$(document).on("click", "#foo", function() { throwConfirm("bar", doSomethingWithMyRetval) } );
}
function doSomethingWithMyRetval(foo) {
// foo foo foo
console.log("The retval from the confirm was: "+foo);
}
$(document).ready(init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<input id="foo" type="button">
</body>

Related

How to Add Export button in Jquery Custom Datatable

I am using a Web Template for my web site. I am developing with ASP.NET webform. The data will be shown in a Gridview. The Template also has a custom datatable file but without an Export button. I am sharing the js file here. Can anyone help me to edit the jquery and add the export button (PDF, Excel, and Copy)!
Thanks
(function($) {
'use strict';
$.HSCore.components.HSDatatables = {
/**
*
*
* #var Object _baseConfig
*/
_baseConfig: {
paging: true
},
/**
*
*
* #var jQuery pageCollection
*/
pageCollection: $(),
/**
* Initialization of Datatables wrapper.
*
* #param String selector (optional)
* #param Object config (optional)
*
* #return jQuery pageCollection - collection of initialized items.
*/
init: function(selector, config) {
this.collection = selector && $(selector).length ? $(selector) : $();
if (!$(selector).length) return;
this.config = config && $.isPlainObject(config) ?
$.extend({}, this._baseConfig, config) : this._baseConfig;
this.config.itemSelector = selector;
this.initDatatables();
return this.pageCollection;
},
initDatatables: function() {
//Variables
var $self = this,
config = $self.config,
collection = $self.pageCollection;
//Actions
this.collection.each(function(i, el) {
//Variables
var $this = $(el),
$info = $this.data('dt-info'),
$search = $this.data('dt-search'),
$entries = $this.data('dt-entries'),
$pagination = $this.data('dt-pagination'),
$detailsInvoker = $this.data('dt-details-invoker'),
pageLength = $this.data('dt-page-length'),
isResponsive = Boolean($this.data('dt-is-responsive')),
isSelectable = Boolean($this.data('dt-is-selectable')),
isColumnsSearch = Boolean($this.data('dt-is-columns-search')),
isColumnsSearchTheadAfter = Boolean($this.data('dt-is-columns-search-thead-after')),
isShowPaging = Boolean($this.data('dt-is-show-paging')),
scrollHeight = $this.data('dt-scroll-height'),
paginationClasses = $this.data('dt-pagination-classes'),
paginationItemsClasses = $this.data('dt-pagination-items-classes'),
paginationLinksClasses = $this.data('dt-pagination-links-classes'),
paginationNextClasses = $this.data('dt-pagination-next-classes'),
paginationNextLinkClasses = $this.data('dt-pagination-next-link-classes'),
paginationNextLinkMarkup = $this.data('dt-pagination-next-link-markup'),
paginationPrevClasses = $this.data('dt-pagination-prev-classes'),
paginationPrevLinkClasses = $this.data('dt-pagination-prev-link-classes'),
paginationPrevLinkMarkup = $this.data('dt-pagination-prev-link-markup'),
table = $this.DataTable({
pageLength: pageLength,
responsive: isResponsive,
scrollY: scrollHeight ? scrollHeight : '',
scrollCollapse: scrollHeight ? true : false,
paging: isShowPaging ? isShowPaging : config.paging,
drawCallback: function( settings ) {
var api = this.api(),
info = api.page.info();
$($info).html(
'Showing ' + (info.start + 1) + ' to ' + info.end + ' of ' + info.recordsTotal + ' Entries'
);
}
}),
info = table.page.info(),
paginationMarkup = '';
if (scrollHeight) {
$(table.context[0].nScrollBody).mCustomScrollbar({
scrollbarPosition: 'outside'
});
}
$($search).on('keyup', function() {
table.search(this.value).draw();
});
if(isColumnsSearch == true) {
table.columns().every(function () {
var that = this;
if(isColumnsSearchTheadAfter == true) {
$('.dataTables_scrollFoot').insertAfter('.dataTables_scrollHead');
}
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
$('select', this.footer()).on('change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
}
$($entries).on('change', function() {
var val = $(this).val();
table.page.len(val).draw();
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, val);
}
});
if(isSelectable == true) {
$($this).on('change', 'input', function() {
$(this).parents('tr').toggleClass('checked');
})
}
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, info.pages);
}
// Details
$self.details($this, $detailsInvoker, table);
//Actions
collection = collection.add($this);
});
},
pagination: function(target, table, pagiclasses, pagiitemclasses, pagilinksclasses, paginextclasses, paginextlinkclasses, paginextlinkmarkup, pagiprevclasses, pagiprevlinkclasses, pagiprevlinkmarkup, pages) {
var info = table.page.info(),
paginationMarkup = '';
for (var i = 0; i < info.recordsTotal; i++) {
if (i % info.length == 0) {
paginationMarkup += i / info.length == 0 ? '<li class="' + pagiitemclasses + '"><a id="datatablePaginationPage' + (i / info.length) + '" class="' + pagilinksclasses + ' active" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>' : '<li class="' + pagiitemclasses + '"><a id="' + target + (i / info.length) + '" class="' + pagilinksclasses + '" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>';
}
}
$('#' + target).html(
'<ul class="' + pagiclasses + '">\
<li class="' + pagiprevclasses + '">\
<a id="' + target + 'Prev" class="' + pagiprevlinkclasses + '" href="#!" aria-label="Previous">' + pagiprevlinkmarkup + '</a>\
</li>' +
paginationMarkup +
'<li class="' + paginextclasses + '">\
<a id="' + target + 'Next" class="' + paginextlinkclasses + '" href="#!" aria-label="Next">' + paginextlinkmarkup + '</a>\
</li>\
</ul>'
);
$('#' + target + ' [data-dt-page-to]').on('click', function() {
var $page = $(this).data('dt-page-to'),
info = table.page.info();
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$(this).addClass('active');
table.page($page).draw('page');
});
$('#' + target + 'Next').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('next').draw('page');
if ($currentPage.parent().next().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().next().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
$('#' + target + 'Prev').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('previous').draw('page');
if ($currentPage.parent().prev().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().prev().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
},
format: function(value) {
return value;
},
details: function(el, invoker, table) {
if (!invoker) return;
//Variables
var $self = this;
$(el).on('click', invoker, function() {
var tr = $(this).closest('tr'),
row = table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('opened');
} else {
row.child($self.format(tr.data('details'))).show();
tr.addClass('opened');
}
});
}
};
})(jQuery);

problems with storing getjson request in variable

I'm having troubles with getting a variable from a getJSON() request. I have the following three functions:
function getPcLatitude() { // onchange
var funcid = "get_postcode_latitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLatitude) {
if (dataLatitude == null) {
//..
} else {
var myLatitude = 0;
for (var i=0;i<dataLatitude.length;i++){
myLatitude = dataLatitude[i].pc_latitude;
}
return parseFloat(myLatitude);
//alert(myLatitude);
}
});
}
function getPcLongitude() { // onchange
var funcid = "get_postcode_longitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLongitude) {
if (dataLongitude == null) {
//..
} else {
var myLongitude = 0;
for (var i=0;i<dataLongitude.length;i++){
myLongitude = dataLongitude[i].pc_longitude;
}
return parseFloat(myLongitude);
//alert(myLongitude);
}
});
}
function getTop5Postcode() { // onchange
setTimeout(function() {
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var latitude = getPcLatitude();
var longitude = getPcLongitude();
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}, 0);
}
Form some reason the
var latitude = getPcLatitude();
var longitude = getPcLongitude();
parts don't work / don't get a value form the functions. When I change the return in both functions into an alert() it does give me the expected values, so those two functions work.
When I set the two variables directly, like so:
var latitude = 5215;
var longitude = 538;
then the getTop5Postcode() function does work and fills the table.
Any help on this?
Regards, Bart
Do not forget that JavaScript is asynchronous, so by the time you reach the return statement, the request is probably not done yet. You can use a promise, something like:
$.getJSON(....).then(function(value){//do what you want to do here})
Both your functions (getPcLatitude and getPcLongitude) are returning nothing because the return statement is inside a callback from an asynchronous request, and that's why an alert show the correct value.
I would suggest you to change both methods signature adding a callback parameter.
function getPcLatitude(callback) {
...
}
function getPcLongitude(callback) {
...
}
And instead of returning you should pass the value to the callback:
callback(parseFloat(myLatitude));
callback(parseFloat(myLongitude));
And your last function would be somehting like that:
function getTop5Postcode() { // onchange
setTimeout(function() {
var latitude;
var longitude;
getPcLatitude(function(lat) {
latitude = lat;
getTop5(); // Here you call the next function because you can't be sure what response will come first.
});
getPcLongitude(function(longi) {
longitude = longi;
getTop5();
});
function getTop5() {
if (!latitude || !longitude) {
return; // This function won't continue if some of the values are undefined, null, false, empty or 0. You may want to change that.
}
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}
}, 0);
}
Of course, this is far away from the perfect solution for your problem but it should work!
And I did not test this code.
I solved this by doing some extra stuff in mysql queries. Now I only have to use the main function.
Things work now! Thanks for all the help!

How can I pass a variable within a function. Javascript

This is my code, everything works, but I can not pass the variable "obj" inside the function $$('.create-popup').on('click', function () {...
I need to get the data into the variable {{contenido}}, but I can not access.
Create-popup function works, the popup is generated, but I can not get the data variable to pass them into the function.
myApp.showPreloader('Cargando notas');
$$.getJSON("http://fabianleguizamon.com.ar/wp-json/wp/v2/posts", function(jsondata){
myApp.hidePreloader();
var old=jsondata;
//next - your code
//var old=data;
var obj=[];
for(var i=0;i<old.length;i++){
var tit=old[i]["title"];
var con=old[i]["content"];
var exc=old[i]["excerpt"];
var fec=new Date(old[i]["date_gmt"]);
var fec2 = fec.getDate() + '/' + (fec.getMonth() + 1) + '/' + fec.getFullYear();
var img=old[i]["better_featured_image"]["media_details"]["sizes"]["oblique-entry-thumb"];
var bdy=old[i]["acf"];
var o=[];
var t={};
var z={};
t.id=i+1;
t.titulo=tit["rendered"];
t.contenido=con["rendered"];
t.bajada=exc["rendered"];
t.enlace=img["source_url"];
t.fecha=fec2;
obj.push(t);
}
var myList = myApp.virtualList('.list-block.media-list.virtual-list.accordion-list', {
items: obj,
// Custom search function for searchbar
searchAll: function (query, items) {
var found = [];
for (var i = 0; i < items.length; i++) {
if (items[i].title.indexOf(query) >= 0 || query.trim() === '') found.push(i);
}
return found; //return array with mathced indexes
},
template:
'<li class="accordion-item">' +
'<a href="#" data-popup="popup{{id}}" class="item-link item-content create-popup">' +
'<div class="item-inner">' +
'<div class="item-title-row">' +
'<div class="item-title">{{titulo}}</div>' +
'</div>' +
'<div class="item-text">{{fecha}}</div>' +
'</div>' +
'</a>',
height: 100,
});
$$('.create-popup').on('click', function () {
var popupHTML = '<div class="popup">'+
'<div class="content-block">'+
'<p>{{contenido}}</p>'+ <---- I can't access here!!!!!
'<p>Cerrar</p>'+
'</div>'+
'</div>'
myApp.popup(popupHTML);
});
});

multiple onload error in HTML

HTML:-
In the body tag I have used onload="variable2.init() ; variable1.init();".
JavaScript:-
var variable1 = {
rssUrl: 'http://feeds.feedburner.com/football-italia/pAjS',
init: function() {
this.getRSS();
},
getRSS: function() {
jQuery.getFeed({
url: variable1.rssUrl,
success: function showFeed(feed) {
variable1.parseRSS(feed);
}
});
},
parseRSS: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable1.parsefootballitaliaRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content1" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens1\', \'#blog_posts1\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts1\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen1').html(main);
jQuery('#blog_posts1').html(posts);
},
parsefootballitaliaRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
var variable2 = {
weatherRSS: 'http://feeds.feedburner.com/go/ELkW',
init: function() {
this.getWeatherRSS();
},
getWeatherRSS: function() {
jQuery.getFeed({
url: variable2.weatherRSS,
success: function showFeed(feed) {
variable2.parseWeather(feed);
}
});
},
parseWeather: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable2.parsegoRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content2" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens2\', \'#blog_posts2\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts2\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen2').html(main);
jQuery('#blog_posts2').html(posts);
},
parsegoRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
When I run the program it only reads one of the variables i.e. either 1 or 2.
How can I correct them to read both the variables?
Use this.
<script type="text/javascript">
window.onload = function() {
variable1.init();
variable2.init();
}
</script>
Try this
<body onload="callFunctions()">
JS-
function callFunctions()
{
variable1.init();
variable2.init();
}
Update-
Also
there are other different ways to call multiple functions on page load
Hope it hepls you.

How can I open with blank page on this rss javascript nor html?

I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// 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://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
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>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</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];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) 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>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'

Categories

Resources