My end goal is to have a home page that pulls RSS feeds and displays them on my home page for my personal website. This is all done from the client side and I'm not looking to build a server site script to do this (I will though only if no other way is possible).
Below is the page load code. (I don't think this is a problem area but it nice to see the starting point)
$(document).ready(function () { // Here
loadpageF(); //<- problems is in this function
GetBackGround(document.body); //this just messes with the css of the site
});
function loadpageF() {
addTableFeed("http://www.npr.org/rss/rss.php?id=1001");
addTableFeed("http://news.yahoo.com/rss/odd");
addTableFeed("http://www.nfl.com/rss/rsslanding?searchString=team&abbr=DAL");
addTableFeed("http://www.npr.org/rss/rss.php?id=1007");
$(".MainArea").css("width",$("iframe").length * (270));
}
//This function sets up where the RSS data will be place after formatting
function addTableFeed(feedlink) {
var numOfCell = maintb.getElementsByTagName("iframe").length;
maintb.innerHTML += "<iframe id='f" + numOfCell + "' class='iframeFeed'></iframe>";
getRSSFeed(feedlink, "f" + numOfCell);
}
This code basically calls a function for each rss to add and iframe and the passes the iframe id and the URL to another function (shown below and I am 99% sure is the problem) which getting the data.
function getRSSFeed(feedlink, iframeid) {
/*var xmlhttp; old way I did it below realizing it did not work in firefox
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var hold = xmlhttp.responseText
loadData(hold, iframeid);
}
}
xmlhttp.open("get", feedlink, false);
xmlhttp.send();*/ //end of the old way
//new way to try to use JSON of course failing at my in goal
$.ajax({
type: "GET",
url: feedlink,
async: true,
dataType: "text",
success: function(data){
loadData(data, iframeid);
},
error: function(data, statusCode) {
alert("ERROR: "+data.error)
}
});}
The function loadData works fine when called, however it is not called for the Yahoo.com and NFL.com feed. Instead I get an alert as shown below.
//Note I has to transcribe from dialog box there may be errors
ERROR: function () {
if( list ) {
// First, we save the current length
var start = list length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
¡f( jQuery.isFunction( arg ) && (!options unique || self.has( arg)
list .push( arg);
else if( arg && arg.length ) {
// Inspect recursively
add( arg);
}
});
})( arguments);
//Do we need to add the callbacks to the
// current firing batch?
if (firing ) (
firingLength = list length;
//wiIh memory, if we’re not firing then
// we should call right away
J else if ( memory ) (
firingstart = start;
fire( memory);
Just in case it is needed, below is the load data code.
function loadData(xml, ifid) {
var htmlStr;
var artCount = 0;
var $xml = $($.parseXML(xml));
$("#" + ifid)[0].contentDocument.open();
$("#" + ifid)[0].contentDocument.close();
$("#" + ifid)[0].contentDocument.write("<head><link rel='Stylesheet' type='text/css' href='" + document.getElementById("StyleSheet").href + "' /></head>");
//RSS 2.0 handler
$xml.find("channel item").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("description").text();
var link = $article.find("link").text();
var pubDate = $article.find("pubDate").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" +artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//Atom 1.0 handler
$xml.find("feed entry").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("summary").text();
var link = $article.find("link").attr("href");
var pubDate = $article.find("published").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" + artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//$("#" + ifid).contents().find(".ArticalBody").hide();
}
Please forgive me for any typos or spelling errors. I can also post the whole web page if needed.
Related
So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });
I am getting no response from a 2nd ajax request. I am trying to display an google information window on google map that contains only a single tab when a certain criteria is matched otherwise I want to display two tabs. I thought I could easily implement this with another marker function with tailored behaviour, but I receive no response. Any help on this is always appreciated. Thanks in advance.
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ecoli_array = [];
var marker = this;
var str = "";
var beach_status; // beach_status flag
// load gif before ajax request completes
infoWindow.setContent('<img src="img/loading.gif" alt="loading data"/>');
infoWindow.open(map, marker);
// override beach data when a beach is closed
beach_status = this.getBeachStatus();
beach_status = beach_status.toLowerCase();
if (beach_status === 'closed') {
str = [
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>' + this.status_description + '</p>'
].join('');
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
} else {
// chained ajax invocations
if ( this.displayOnlyAlgaeResults === false ) {
// Standard Use case
$.when(this.getEcoliData(), this.getAlgaeData()).done(function (data1, data2) {
str += marker.getHeader() + marker.afterGetEcoliData(data1[0].rows);
str += marker.afterGetAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
}else{
// Algae Only Use Case
var d = this.getOnlyAlgaeData();
console.log(d);
$.when( this.getOnlyAlgaeData() ).done(function ( rsp ) {
//console.log(rsp);
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
//str += marker.afterGetOnlyAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
} // end inner if else
} // end outer if else
}); // End click event handler
getOnlyAlgaeData: function () { // begin getAlgaeData
var obj;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=xxxxx&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + this.beach_id;
var query = "SELECT * FROM xxxx "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}, // end getAlgaeData method
// added afterGetOnlyAlgaeData
afterGetOnlyAlgaeData: function (data) {
var algae_rows_str = "";
algae_rows = data;
var algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data">',
'<tr>',
'<th>Sample Date</th>',
'<th class="centerText">Blue Green Algae Cells <br/>(cells/ mL) </th>',
'<th>Recreational Water Quality Objective <br/>(100,000 cells/mL)</th>',
'<th class="centerText">Algal Toxin Microcystin <br/> (μg/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 μg/L)</th>', // &mu instead of u
'</tr>'
].join('');
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>This season, no algal blooms have been reported at this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
//algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td></tr>';
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
}, // end afterGetOnlyAlgaeData
}); // ====================end marker
I essentially copied two identical functions that work, gave them a slightly different name and customized each function to display 1 tab instead of two, but I get no response.
Thoughts?
thanks for the help, it ended up being something simple.
I was incorrectly referencing the response. Ie. I change the following line:
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
to
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp.rows );
Geez!
I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}
You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}
I've been following this answer in an attempt to write good asynchronous js - but I can't quite figure out what's going wrong for me.
I'm using autocomplete to request a specific set of files from the server, but for some datasets these files may not exist (i.e, there may be one, or up to four files). If they do exist, I want to append .html to include them.
The images don't load unless I add
async: false
to the .ajax call, which makes the callback redundant.
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
$.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
})(i);
}
Then image_html contains html for only those images that exist.
$('#outputcontent').html(outer_html + image_html + outer_html_end);
Can anyone explain to my misunderstanding here please? Why isn't image_html being populated?
EDIT: 'full' code below. I use jquery autocomplete to pull from the stellar_comp array, then for those with properties that exist (some are blank), html is generated. Within that is the ajax call.
$(function () {
var stellar_comp = [
{
value:'X0005-28',
data: {
set0: {
aperture:'X2105-28',
secat:'X025-18',
set:'1',
run:'r06',
continuumFilter:'J',
narrowBandFilter:'638/28',
numberOfSources:'1',
priorityCode:'1'
etc... etc ...
},
},
];
$('#autocomplete').autocomplete({
lookup: stellar_comp,
onSelect: function (suggestion) {
var path_Value = 'data/' + suggestion.value + '/';
var outer_html = '<h1>' + suggestion.value + ' </h1> <div class="container">';
var outer_html_end = '</div>';
for (var category in suggestion.data) {
if (suggestion.data.hasOwnProperty(category)) {
if (suggestion.data[category].aperture) {
summary_table_contents = '<tr> <td>' + suggestion.data[category].set + '</td> <td>' + suggestion.data[category].run + '</td> <td>' + suggestion.data[category].continuumFilter + '</td> <td>' + suggestion.data[category].narrowBandFilter + '</td> <td>' + suggestion.data[category].numberOfSources + '</td> <td>' + suggestion.data[category].priorityCode + '</td></tr> ';
summary_table += summary_table_contents;
var aperturePlot = suggestion.data[category].aperture + '_' + suggestion.data[category].run;
var seCATPlot = suggestion.data[category].secat + '_Rsub_ss_' + suggestion.data[category].run;
var aperture_match = suggestion.data[category].aperture_match;
cog = path_Plots + aperturePlot + '_cog';
sbprof = path_Plots + aperturePlot + '_sbprof';
thumb_cog = '';
thumb_cog_temp = '';
thumb_sb = '';
temp='';
for (var i = 1; i < 5; i++) {
(function (counter) {
function some_function(callback) {
$.ajax({
type: "GET",
url: cog + counter + "_1.jpg",
async: false,
success: function (result) {
callback(counter);
}
});
}
some_function(function (num) {
var thumb_cog_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + cog + num + '_1.jpg"> <img class="img-thumbnail" src="' + cog + num + '_4.jpg" /></a> <div class="caption"><h5>' + suggestion.value + ':S' + num + '</h5></div></div>';
var thumb_sb_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + sbprof + num + '_1.jpg"><img class="img-thumbnail" src="' + sbprof + num + '_4.jpg" /></a><div class="caption"><h5>' + suggestion.value + ':S' + num + ' </h5></div></div>';
console.log(num, counter);
thumb_cog += thumb_cog_temp;
thumb_sb += thumb_sb_temp;
});
})(i);
}
cog_sbprofile_row='<div class="row"><h3>C o G</h3> ' + thumb_cog + '</div><div class="row"><h3>Profiles</h3> ' + thumb_sb + '</div>';
console.log(cog_sbprofile_row);
body_html += aperture_row;
body_html += seCAT_row;
body_html += aperture_match_row;
body_html += pixel_map_row;
body_html += skyprofile_row;
body_html += cog_sbprofile_row;
body_html += '<hr>';
};
};
};
top_html += summary_table + '</tbody> </table> </div></div> <hr>';
$('#outputcontent').html(outer_html + hipass_container + top_html + body_html + outer_html_end);
}
});
});
The current problem is due to using the resulting HTML string, before it has been created via multiple asynchronous calls. You need to either defer that operation until all loads are completed, or change the situation so it is not dependent on final completion (progressive loading looks busier anyway).
Personally I would simply insert placeholders for the images as you loop and insert each as they load. This way the order is retained. You can even do effects (fade etc) on each as they load:
var wrapper = "";
for (var i = 1; i < 5; i++) {
// Make a placeholder element for each image we expect
wrapper += '<div class="thumbnail" id="thumb_' + i + '">'
(function (num) {
// call the function
$.ajax({
type: "GET",
url: num + "_1.jpg",
success: function (result) {
var image_temp = '<img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num;
// Insert new image into unique element and fade it in
$('#thumb_'+num).append(image_temp).fadeIn();
}
});
})(i);
}
// Append all placeholders immediately - these will be appended to as each image is loaded
$('#outputcontent').html(outer_html + wrappers + outer_html_end);
Update:
As Alnitak points out, the whole exercise is a little pointless as you are ignoring the result returned from the Ajax call anyway, so you might as well drop the Ajax call (which adds no value) and simply build the image elements on the fly server-side :)
You have to do the appending after all ajax requests finish their jobs. First define this:
var after = function(reqs) {
var d = $.Deferred(),
cnt = reqs.length;
if (!cnt) {
d.resolve();
}
var limit = cnt; // separate var just in case reqs are synchronous
// so it won't mess up the loop
for (var i = 0; i < limit; i++) {
reqs[i].always(function() {
cnt--;
if (!cnt) {
d.resolve();
}
});
}
return d.promise();
};
You can use $.when instead of this but if one of the requests results in 404 it won't wait for others. Now:
var image_html = "",
requests = [];
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
return $.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
var req = ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
requests.push(req); // push the request to the array
})(i);
}
after(requests).done(function() {
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
Note that I've added return $.ajax(...).
BTW: what's the point of defining ajaxTest function? Just put everything in an anonymous callback.
Read more about deferred objects and promises here:
http://api.jquery.com/category/deferred-object/
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
or just google it.
EDIT: if the order is important then you just have to tweak the callback function a bit:
var image_html = []; // array instead of string
// some code...
var req = ajaxTest(function (num) {
// ...
image_html[counter] = image_temp;
});
// some code...
after(requests).done(function() {
image_html = image_html.join("");
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
BACKGROUND
My app consist of 2 static pages and x number of dynamically generated pages. The number of dynamically generated pages varies from time to time. My first static page is a login page. Once you login you are taken to the 2nd static page which is a welcome screen and then you can start swiping left to view the dynamically generated pages.
What i want to achieve
I basically want to get the page id of the currently active page. As in i want to get the id of the page i am currently viewing. i tried the following
pageId = $('body').pagecontainer('getActivePage').prop("id");
console.log('==========================>THIS IS ID: '+pageId);
It only gives me the page id of the 2nd static page and not the id of the dynamically generated pages because when i swipe left to view my dyanamically generated pages the console log does not print at all.
Here is the code for the entire relevant js
var widgetNames = new Array();
var widgetId = new Array();
//ActivePageId
var pageId = ''
$(document).on("pagecreate", function () {
$("body > [data-role='panel']").panel().enhanceWithin();
});
$(document).on('pagecreate', '#page1', function () {
$("#log").on('click', function () {
$.ajax({
url: "script.login",
type: "GET",
data: {
'page': 'create_user',
'access': 'user',
'username': $("input[name='username']").val(),
'password': $("input[name='password']").val()
},
dataType: "text",
success: function (html) {
console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
for (var i = 0; i < res.length; i++) {
var temp = res[i].split(',');
if (temp.length >= 3) {
widgetNames[i] = (temp[2].replace('");', '')).replace('"', '');
widgetId[i] = temp[1].replace("'", "").replace("'", "").replace(/ /g, '');
}
}
var AllWidgets = ''
var testwidget = new Array();
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for (var i = 0; i < tempWidgetContent.length; i++) {
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{') + 1);
testwidget[i] = widgetContent.replace("site +", "");
}
var widgetPart = new Array();
for (var i = 0; i < widgetNames.length; i++) {
var pageHeaderPart = "<div data-role='page' id='" + widgetId[i] + "' data-pageindex='" + i + "' class='dynPageClass'><div data-role='header' data-position='fixed'><a data-iconpos='notext' href='#panel' data-role='button' data-icon='flat-menu'></a><h1>BASKETBALL FANATICO</h1><a data-iconpos='notext' href='#page2' data-role='button' data-icon='home' title='Home'>Home</a></div> <div data-role='content'>";
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='b'>" + widgetNames[i] + "</div>";
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#989797; font-size: 75pt;\" id=widgetContainer_' + widgetId[i] + '></DIV><SCRIPT>' + 'function UpdateWidgetDiv' + widgetId[i] + '() {' + testwidget[i] + '$(\"#widgetContainer_' + widgetId[i] + '").html(counterValue);' + '}' + 'setInterval(function(){UpdateWidgetDiv' + widgetId[i] + '()},3000)' + '</SCRIPT>';
AllWidgets += '<a href="#' + widgetId[i] + '" class="widgetLink" data-theme="b" data-role="button" >' + widgetNames[i] + '</a>';
var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
//Get Active Page ID
$( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
pageId = $('body').pagecontainer('getActivePage').prop("id");
alert( "The page id of this page is: " + pageId );
});
}
});
});
});
Please advise and sorry if it is a bad question to ask as I am a beginner.
You were getting the active page from within the ajax call, not when swiping to a new page.
The detection code needs to fire when you are on one of the dynamic pages, show you could use pagecontainershow to detect the pageID as soon as the page displays (http://api.jquerymobile.com/pagecontainer/#event-show).
$( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
});
UPDATE: Using pageid when updating pages:
It looks like you want an update every 3 seconds on the active page. so create a function for the entire page:
function UpdateActivePage(){
//get active page
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
//figure out index
var idx;
for (var i=0; i<widgetId.length; i++){
if (widgetId[i] == pageid){
idx = i;
break;
}
}
//run your update
eval(testwidget[idx]);
$("#widgetContainer_" + pageid).html(updated stuff);
}
setInterval(UpdateActivePage, 3000);