JavaScript / JSON Linked Listview - Loading a New Panel - javascript

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>

Related

JavaScript: Remove Double Quotes - JSON.Stringify()

After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this?
Here is my code -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
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>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
</script>
Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string.
Uncomment your stringify lines and it works.

jQuery fill the prepared HTML div dynamically with JSON data

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...

Getting the currently active page id

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);

Creating Pages Dynamically

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});
});

The right use of jQuery? Owl carousel

For my project I use the OwlCarousel. http://www.owlgraphic.com/owlcarousel/#more-demos
I managed to get 3 carousels on my page. But I think the page is getting to slow. Is there a possibility that I make to many steps?
Actually I don't need to read the json file because I store it in the localStorage one page before. But I didn't know how to delete it out without corrupting the code.
So the main question is how to make just one jQuery call to fill all 3 carousels?
This is the code I use to call the carousel:
<div id="dodatni1" style="visibility:hidden" >
<div id="owl-demo" class="owl-carousel" ></div>
</div>
<div id="dodatni2" style="visibility:hidden" >
<div id="owl-demo2" class="owl-carousel" ></div>
</div>
<div id="dodatni3" style="visibility:hidden" >
<div id="owl-demo3" class="owl-carousel" ></div>
</div>
And this is the carousel code:
$(document).ready(function() {
$("#owl-demo").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg ="http://www.spleticna.si/images/"+localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3239){
content += "<a href=\"produkt.html?id=" + j + "&slider=a\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo").html(content);
}
});
$(document).ready(function() {
$("#owl-demo2").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 2615){
content += "<a href=\"produkt.html?id=" + j + "&slider=b\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo2").html(content);
}
});
$(document).ready(function() {
$("#owl-demo3").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});
I'm not sure how much speed you could get but you can rewrite your JS:
$(document).ready(function(){
//Assuming they all use the same data source/settings?
$("#owl-demo3,#owl-demo2,#owl-demo1").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});

Categories