What i have:
JSON with id, name, position, department and address.
That same JSON have over 1000 random employees looped to a table.
Every person have a custom attribute (user_id) and same css class for hovering.
One hidden prepared and styled div for information when is hovered on one employee.
What i need:
I need when i hover on some employee to display all that employee information like name, position, department and address. Keep in mind that hover is working, but informations are still static. So basically, my logic is when custom attr user_id and JSON id match = fill the html.
How can i do that?
var xmlhttp = new XMLHttpRequest();
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
employees = JSON.parse(this.responseText);
write(employees);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function write(arr) {
var i;
var out = '<table>';
for(i = 0; i < arr.length; i++) {
out += '<tr>';
out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
out += '<td>' + arr[i].position + '</td>';
out += '</tr>';
}
out += '</table>';
document.getElementById('employees').innerHTML = out;
}
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('.hoverKartX').hover(function(e) {
//$(this).parent().find(".hoverKart").show();
$(".hoverKart").show();
}, function() {
$('.hoverKart').hide();
});
$('.hoverKartX').mousemove(function(e) {
$(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
// preventing 'falling' to the right on smaller screen
if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
$(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
};
// preventing 'falling from the bottom of the page'
if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
$(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
}
});
});
.hoverKart {
position: absolute;
width: 400px;
height: 220px;
border-radius: 25px;
border: 1px solid #999;
z-index: 1;
display: none;
background: #fff;
}
<!-- hidden div-->
<div class="hoverKart">
<div class="container">
<div class="cardTop"><p><!-- JSON DATA (ID) --></p></div>
<div class="imgHolder">
<img class="employee" src="img/img.jpg" alt="employee image">
<img class="eLogo" src="img/logo.jpg" alt="logo">
</div>
<div class="eInformation">
<p class="eName"><!-- JSON DATA (NAME) --></p>
<p class="ePos"><!-- JSON DATA (DEPARTMENT) --></p>
<div class="eDep">
<img src="img/icons-dep/5.png" alt="department logo">
</div>
<p class="eOp">Operations</p>
<p class="eOp2"><!-- JSON DATA (ADDRESS) --></p>
</div>
</div>
</div>
<div id="employees"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have update your code and created a fiddle:
Check the working Fiddle.
$(function(){
var xmlhttp = new XMLHttpRequest();
var myGlobalJson;
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
employees = JSON.parse(this.responseText);
myGlobalJson = employees;
write(employees);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function write(arr) {
var i;
var out = '<table>';
for(i = 0; i < arr.length; i++) {
out += '<tr>';
out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
out += '<td>' + arr[i].position + '</td>';
out += '</tr>';
}
out += '</table>';
document.getElementById('employees').innerHTML = out;
bindMethods();
}
//$(function() {
function bindMethods(){
var moveLeft = 20;
var moveDown = 10;
$('.hoverKartX').hover(function(e) {
//$(this).parent().find(".hoverKart").show();
var currentUserId = parseInt(($(this).attr('user_id')));
//console.log(myGlobalJson);
//console.log(typeof parseInt($(this).attr('user_id')));
$.each(myGlobalJson, function(i, item) {
//console.log($(this).attr('user_id'));
if(item.id === currentUserId){
$(".hoverKart .cardTop").html(item.id);
$(".hoverKart .eName").html(item.name);
$(".hoverKart .ePos").html(item.position);
$(".hoverKart .eOp2").html(item.address);
return false;
}
});
$(".hoverKart").show();
}, function() {
$('.hoverKart').hide();
});
$('.hoverKartX').mousemove(function(e) {
$(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
// preventing 'falling' to the right on smaller screen
if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
$(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
};
// preventing 'falling from the bottom of the page'
if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
$(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
}
});
}
//});
});
There were some issues in existing code:
You should bind hover method to field only when your write method execution is finished. Otherwise, it's working will be inconsistent, depending on how fast table is created.
I hope, It will solve your purpose.
Alright apology for different answer as it's whole different way to fix this issue like below,
As your main problem is your "hoverKartX" jquery events are not binded to any elements because your html elements are generated dynamically from xmlhttp, so first you need to make sure your events are binded to your html elements after generating it, probably you need to refactor your code and move your $('.hoverKartX').hover()... and $('.hoverKartX').mousemove()... in your function write(arr) as you had attached your mousehover and mousemove event's code in global context which will bind to no html element at the time of page load because you are generating these elements dynamically using xmlhttp,
then access your custom html attribute user_id by using jquery's attr like $(this).attr('user_id') in your mousehover or mousemove event and do whatever you want to do...
Related
I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});
I am trying to write some JavaScript code to load JSON from a URL and then display it in a linked listview that navigates to a new panel within the webapp that I am creating. I have successfully rendered the listview from the JSON data however, I cannot seem to get a new panel open. Any ideas? My code so far it below -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var panel_view = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
panel_view += '<div class="panel" data-title="'+obj[i].name.first+'" id="item_profiles'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+obj[i].name.first+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+obj[i].name.first+'</p></div>';
$('#profiles_panel').after(panel_view);
</script>
EDITED -
So, the purpose of this is to achieve the below code to use just Native JavaScript as oppose to jQuery. Here is the jQuery version of the code -
<script type="text/javascript">
$(document).ready(function () {
var panel_view_admissions = "";
$.getJSON( 'http://localhost:3000/admissions', function(data) {
$.each( data, function(i, name) {
$('ul.list-admissions').append('<li>'+name.title+'</li>');
panel_view_admissions += '<div class="panel" data-title="'+name.title+'" id="item_admissions'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+name.image+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+name.content+'</p></div>';
});
$('#admissions_panel').after(panel_view_admissions);
});
});
</script>
I have pages of scrapped data coming from the db and displaying that in a table (which works fine). Then I have another query from the db to only get the error rows from that scrapped data and to display that data in a div in the header. This way the user knows what data to change.
I'm having trouble allowing the user to change pages and then get the first row of that page's error data. Right now what I'm doing is creating an index variable and using that as a count and allowing the user to click through rows one at a time and then it changes to the next page if there is no more error data for that page.
How can I get it so the user is able to change the pages freely and then get the correct rows for that data and be able to click up or down through the objects for that page?
Here is my header where the error data and page header data is stored:
<div id="pageEditDiv">
<div class="arrowIconsDiv">
<img src="images/up-arrow.png" class="arrowIcons" id="arrowUpPage">
<img src="images/down-arrow.png" class="arrowIcons" id="arrowDownPage">
</div>
<div id="pageSummary">
<table id="headerPagesTable">
<thead><tr><th>Page Num</th><th>Type</th><th>Month</th><th>Name</th><th>Reg No.</th><th>Rrc District</th></tr></thead>
<tbody id="pagesTableBody"></tbody>
</table>
</div>
<div id="pagesTable" class="hidden"></div>
</div>
<div id="rowEditDiv">
<div class="arrowIconsDiv">
<img src="images/up-arrow.png" class="arrowIcons" id="arrowUpRow">
<img src="images/down-arrow.png" class="arrowIcons" id="arrowDownRow">
</div>
<div id="editableRowToEdit" contenteditable>
<table id="editableRowTable">
<tbody id="pagesRowToEdit"></tbody>
</table>
</div>
</div>
Here is where I get the error row data:
$.ajax({
type: 'POST',
url: 'qry/getPageReceipts.php',
async: true,
data: {FileId: fileId, PageNum: getPageNum, RowNum: rowNum},
success: function(response) {
recPageData = JSON.parse(response);
//check if data exists or not
recPD = {};
if(recPageData.length == 0) {
recPageDateEmpty = 1;
} else {
//map the data
recPD = recPageData.PageNum.map((x,i) => ({
pageNum: x,
rowNum: recPageData["RowNum"][i],
cName: recPageData["CustomerName"][i],
fName: recPageData["FacilityName"][i],
rrcNum: recPageData["RrcNum"][i],
rrcType: recPageData["RrcNumType"][i],
volume: recPageData["Volume"][i]
}));
//sort the data
recPD.sort(function(a,b) {
if(a.pageNum == b.pageNum) {
return (a.rowNum - b.rowNum);
} else {
return (a.pageNum - b.pageNum);
}
});
for(var i=0; i<recPD.length; i++) {
recPD[i].index = i;
}
}
drawPageForm();
drawRowEditForm();
}
});
Here is where I draw the page summary data for the user to click up and down the pages:
function drawPageForm() {
//clear div to begin with
$(".pagesMonth").html();
$("#pagesTableBody").empty();
var getPages = '<table><thead><tr><th>Page Num</th><th>Type</th><th>Month</th><th>Name</th><th>Reg No.</th><th>Rrc District</th></tr></thead><tbody>';
for(var i=0; i<getPagesResponse.length; i++) {
getPages += '<tr class="getPagesRowEdit"><td>' + getPagesResponse["PageNum"][i] + '</td><td class="pagesPageType">' + getPagesResponse["PageType"][i] + '</td><td class="pagesMonth">' + getPagesResponse["ReportingMonth"][i] + '</td><td class="pagesFilerName">' + getPagesResponse["FilerName"][i] + '</td><td class="pagesFilerRegNo">' + getPagesResponse["FilerRegNo"][i] + '</td><td class="pagesRrcDistrict">' + getPagesResponse["RrcDistrict"][i] + '</td></tr>';
}
getPages += '</tbody></table>';
//add table to div
$("#pagesTable").html(getPages);
//PAGES
//delcare single object for page summary
gPT = {
gPRE : $(".getPagesRowEdit").eq(0),
pNum : $(".getPagesRowEdit").find("td").eq(0).text(),
pTB : $("#pagesTableBody"),
aUP : $("#arrowUpPage"),
aDP : $("#arrowDownPage"),
place : function(row) {
gPT.pTB.empty();
clone = row.clone(true);
clone.appendTo(gPT.pTB);
}
}
//add row to div
gPT.place(gPT.gPRE);
//arrow up
gPT.aUP.on("click", function() {
prev = gPT.gPRE.prev();
gPT.gPRE = prev.is("tr") ? prev : gPT.gPRE;
gPT.place(gPT.gPRE);
gPT.pNum = $(".getPagesRowEdit").find("td").eq(0).text();
pageNum = gPT.pNum;
reDrawTextContentandPDF();
});
//arrow down
gPT.aDP.on("click", function() {
next = gPT.gPRE.next();
gPT.gPRE = next.is("tr") ? next : gPT.gPRE;
gPT.place(gPT.gPRE);
gPT.pNum = $(".getPagesRowEdit").find("td").eq(0).text();
pageNum = gPT.pNum;
reDrawTextContentandPDF();
});
}
Here is where I draw the row error data for the user to click up and down each row of data for that specific page:
function drawRowEditForm() {
//get the current page type
pageTypeValue = $(".pagesPageType").html();
//empty row
$("#pagesRowToEdit").empty();
//find correct row
recPD.find(findRecPageIndex);
//match row with rawText row
findMatchRowNum = $("#pagesRowToEdit").find("tr").eq(0).find("td").eq(0).text();
findMatchRowNum = findMatchRowNum - 1;
matchedRow = $(".rowToEdit").eq(findMatchRowNum);
matchedRow.addClass("selected");
//scroll div to visible row
$("#textCodeDiv").animate({
scrollTop: $(".selected").offset().top
},'slow');
//click arrow up
$("#arrowUpRow").unbind("click").click(function() {
clickRowArrowUp();
});
//click arrow down
$("#arrowDownRow").unbind("click").click(function() {
clickRowArrowDown();
});
}
function clickRowArrowUp() {
$("#pagesRowToEdit").empty();
if($(".selected")) {
$(".selected").removeClass("selected");
}
recRowIndex--;
if(recPD.find(findRecPageIndex)) {
drawRowEditForm();
} else {
prev = gPT.gPRE.prev();
gPT.gPRE = prev.is("tr") ? prev : gPT.gPRE;
gPT.place(gPT.gPRE);
gPT.pNum = $(".getPagesRowEdit").find("td").eq(0).text();
pageNum = gPT.pNum;
reDrawTextContentandPDF();
}
}
function clickArrowDown() {
$("#pagesRowToEdit").empty();
if($(".selected")) {
$(".selected").removeClass("selected");
}
recRowIndex++;
if(recPD.find(findRecPageIndex)) {
drawRowEditForm();
} else {
next = gPT.gPRE.next();
gPT.gPRE = next.is("tr") ? next : gPT.gPRE;
gPT.place(gPT.gPRE);
gPT.pNum = $(".getPagesRowEdit").find("td").eq(0).text();
pageNum = gPT.pNum;
reDrawTextContentandPDF();
}
}
//match the row to the error data and display in header
function findRecPageIndex(el) {
if(el.index === recRowIndex && el.pageNum === pageNum) {
return $("#pagesRowToEdit").append("<tr id='recTR'><td class='hidden'>" + el.rowNum + "</td><td>" + el.cName + "</td><td>" + el.fName + "</td><td>" + el.rrcNum + "</td><td>" + el.rrcType + "</td><td>" + el.volume + "</td></tr>");
}
}
function findDelPageIndex(el) {
if(el.index === delRowIndex && el.pageNum === pageNum) {
return $("#pagesRowToEdit").append("<tr id='delTR'><td class='hidden'>" + el.rowNum + "</td><td>" + el.cName + "</td><td>" + el.fName + "</td><td>" + el.rrcNum + "</td><td>" + el.rrcType + "</td><td>" + el.volume + "</td></tr>");
}
}
So a recap: The user can change pages, BUT then they can't click through the error data. The user can change rows and when there is no more error data on that page it will then change pages and display the first error data row.
What I need to know: is how to allow the user to click through the pages freely and then it be able to determine what page num it is and then display that first error row and allowing the user to click through the correct rows for that page.
Try adding this to your page up and down function:
for(var i=0; i<recPD.length; i++) {
if(pageNum == recPD[i].pageNum) {
recRowIndex = recPD[i].index;
break;
}
}
Here you are looping through the data, checking if the page numbers match and then updating the recRowIndex variable to the lowest index of the error row data.
Hope that works!
I am trying to create a pinterest like webpage using mansory.js and I am having trouble appending the unique description to each image. I know that the last line of my code is wrong but I have no idea how to fix it. I am basically adding all of the description tags into one span for each image.
I've tried looking at several other stackoverflow questions such as jQuery: Add element after another element and add image/s inside a div with jquery
but with no luck.
My entire pen is here http://codepen.io/OG/pen/VLEXgz
HTML
<body>
<h1>Camper Stories</h1>
<div id="content"></div>
</body>
CSS
h1{
text-align:center;
font-family: 'Lobster', cursive; font-size:80px;
color:purple;
}
#content {
width: auto;
margin: 0 auto;
}
.item {
display: inline-block;
float: left;
width: 300px;
height:300px;
margin: 2em;
position:relative;
}
.item img {
width: 300px;
height: auto;
}
JS
var url = 'http://www.freecodecamp.com/stories/hotStories';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var i;
var headlines = [];
//loop through json get need attributes
//for(i = 0; i < arr.length; i++){
for (i = 0; i < 5; i++) {
var headline = arr[i].headline;
headlines.push(headline);
var authorImg = arr[i].author.picture;
//console.log(img);
//error function
//if there is no thumbnail link the get author image
if (img === "") {
$('#content').append('<div class="item">' + '' + '<img id="myImg" src="' + authorImg + '" alt="' + headline + '" />' + '' + '</div>');
} else {
//if there is a thumbnail image then use that image
$('#content').append('<div class="item" id="hi">' + '' + '<img id="myImg" src="' + img + '" alt="' + headline + '" />' + '' + '</div>');
//if there is a 404 error with loading the thumbnail image then use author's image
$('img').one('error', function () {
this.src = '' + authorImg;
})
}
$(arr[i].headline).insertAfter("img");
}
}
See http://codepen.io/anon/pen/YXJvEK Is that what you mean? Append the headline after the corresponding image only?
$("<span>" + arr[i].headline+"</span>").insertAfter($("img").eq(i));
You should build your elements like this:
var wrapper = $("<div />");
var link = $("<href />");
var img = $("<img />");
...
Then add attributes and classes needed and append them to each other.
link.append(img);
wrapper.append(link);
...
In that way your code gets much more maintainable and you can append your span easily to your img (don't know exactly where you want the description).
Edit, since I've got my hands on a pc, here's the code you could use.
function myFunc (data) {
if(typeof data === "undefined") return; // output some error
for (var i = 0; i < data.length; i++) {
var item = data[i];
var upVote = item.rank;
var href = item.link;
var image = (item.image === "") ? item.author.picture : item.image;
var headline = item.headline;
// build elements
var wrapper = $("<div />");
var link = $("<a />");
var img = $("<img />");
var description = $("<span />");
// add attributes and classes
wrapper.addClass("item");
link.attr("href", link);
// you can also set multiple attributes at once
img.attr({"src": image, "alt": headline});
description.text(headline); // text(string) adds string to element
// append elements onto each other
link.append(img);
wrapper.append(link, description);
$("div.content").append(wrapper); // attach elements to DOM
}
}
The following is my code where i am updating the content of the dynamically created pages constantly but the problem is my update function is running every 3 seconds on pages that i am not even viewing. i am not able to fix this.
var widgetNames = new Array();
var widgetId = new Array();
$( 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>";
widgetPart[i] = '<DIV style=\" text-align: center; font-size: 100pt;\" 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 + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
var page = $('body').pagecontainer('getActivePage').prop("id");
console.log('The Page Id is: '+page);
}
});
});
});
In this code i am looking to run the following function
'setInterval(function(){UpdateWidgetDiv'+widgetId[i]+'()},3000)'
only for the page the user is viewing.
Here is a DEMO
When creating the pages, as well as saving the page ids in the widgetId array, I am also saving the current page index as a data attribute on each dynamic page (data-pageindex), and I am assigning a class to all the dynamic pages (dynPageClass):
for (var i = 0; i< 3; i++){
var pageid = 'dynPage' + i;
widgetId.push(pageid);
var p = '<div data-role="page" id="' + pageid + '" data-pageindex="' + i + '" class="dynPageClass">';
p += '<div data-role="header"><h1>Dyn Page' + i + '</h1></div>';
p += '<div role="main" class="ui-content">I am dynamically created</div>';
p += '<div data-role="footer"><h1>Footer</h1></div>';
p += '</div>';
$('body').append($(p));
}
The the swipe code can be handled with one handler on the dynPageClass that handles both swipeleft and swiperight:
$(document).on("swiperight swipeleft", ".dynPageClass", function(e) {
var ind = parseInt($(this).data('pageindex'));
var topageid = "page2";
var rev = true;
if (e.type == 'swiperight'){
if (ind > 0){
topageid = widgetId[ind - 1] ;
}
} else {
rev = false;
if (ind < widgetId.length - 1){
topageid = widgetId[ind + 1] ;
}
}
$.mobile.changePage("#" + topageid, {transition: "slide", reverse: rev});
});
We first get the current page's index from the data attribute and parse it into an integer. Then we see if this is a right or left swipe. If right, and index is greater than 0, we need to go back one dynamic page. Otherwise it is a left swipe and if current page is not the last one, we need to go forward one page.
Your swipeleft code on page2 is left intact:
$(document).on("swipeleft", "#page2", function() {
$.mobile.changePage("#"+widgetId[0], {transition: "slide", reverse: false});
});