Displaying a Jquery image list - javascript

I'm having a problem with the JQuery imagelist. When opening the page for the first time, the list displays correct, the image is shown, title is shown...
Pressing the back button and re-opening the page gives a normal list, no longer the jquery listview?
I'm using a DIV element in my page like this:
<div id="dataDiv">
<ul data-role='listview' id='listing' data-theme='c'>
</ul>
</div>
This gets filled with information retrieved from an api call:
function listApiInfo() {
clearDataDiv();
var parsed = makeApiCallGet("http://someSite/SomeApi");
i = 0;
for (i; i < 15; i++) {
$("#listing").append("<li>"
+ "<img src='" + imageUrl + "' alt='img' class='ui-li-thumb' />"
+ "<h1>" + parsed[i].info + "</h1>"
+ '</a></li>'
);
}
}
on loading the div, i make sure it's an empty list item:
function clearDataDiv() {
$("#dataDiv").html(
"<ul id='listing' data-role='listview' data-theme='c'></ul>");
}
Edit: As suggested by Wibble in the comments, i did look at the cache as the problem.
Giving the div the following option solved the problem:
<div id="dataDiv" onblur='window.location.reload()'>
<ul data-role='listview' id='listing' data-theme='c'>
</ul>
</div>
I'm still not sure if this is the most elegant solution though, it gives a blank screen for a split second.

Related

My menu Link should call a page and a js function. Function fires but page not changed and vice versa

I have a web project with a menu item that needs to call a page, cusomers.php and a javascript function associated with the menu selection. I have chosen to use pure javascript as opposed to jquery. The menu piece is located in include/adminheader.php and looks like this:
<li>View
<ul>
<li><a id="allCustomers" value="all" href="customers.php" >
All Customers</a></li>
<li><a href="customers.php" id="singleCustomer" value="single" >
Single Customer</a></li>
</li>
When the event listener is setup in the external file with ‘onload’:
window.onload = function() {
document.getElementById("allCustomers").addEventListener("click", getCustomers);
document.getElementById("singleCustomer").addEventListener("click", viewCustomer);
}
The event listener is registered and the js function fires with one click, but the page link isn’t followed (i.e. if I’m in the index page when I click menu link to ‘All Customers’ I’m still on index.php after the menu click).
When I setup the same code at the bottom of customers.php the menu link takes me to customers.php but I have to click the link twice the first time, once thereafter to call the js function.
I have also tried adding the listener to the surrounding <li> tag to call the js function and had to click twice the first time for it to fire.
I have read the MDN reference here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener, and the information https://www.w3.org/TR/DOM-Level-3-Events/#event-flow, and of course many stack overflow entries to try to understand how to fix this but am still lost.
I have seen similar questions regarding a js function having to be clicked twice the first time and this was fixed with the onload, but never in conjunction with a link to another page (instead of a href="#"). I’m wondering if this might have something to do with capture but couldn’t figure that out. I realize that I probably should have been able to recognize that another question addresses my problem but if I saw it I did not recognize how to apply to my situration. Please help.
EDIT - js code added need to navigate to page prior to function call
function getCustomers() {
event.preventDefault();
grid.innerHTML = "";
outputTable.innerHTML = "";
grid.className = "grid_4cols";
var ajax = new XMLHttpRequest();
ajax.open("GET", "../controller/admincontroller.php?getCustomers=all", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var arr = JSON.parse(ajax.responseText);
var result = "";
for (var i = 0; i < arr.length; i++) {
result += "<form action='../controller/admincontroller.php' method='POST' >";
result += "<input type='hidden' id='id' name='id' value ='" + arr[i]['ID'] + "'>" ;
result += "<input type='text' name='fname' value='" + arr[i]['fname'] + "'>" ;
result += "<input type='text' name='lname' value='" + arr[i]['lname'] + "'>";
result += "<input type='text' name='email' value='" + arr[i]['email'] + "'>";
result += "<input type='submit' name='selectCustomer' value='Select' ></form>";
}
grid.innerHTML = result;
}
};
}
//not implemented. Not sure how to setup so destination DOM is
//loaded before function call to getCustomers() or viewCustomer()
function goToCustomers() {
location.assign("customers.php"); //used location.replace for first edit
}
add a query string to the href that represents the function that you want to invoke
<li>View
<ul>
<li><a id="allCustomers" value="all" href="customers.php?getCustomers" >All Customers</a></li>
<li><a href="customers.php?viewCustomer" id="singleCustomer" value="single" >Single Customer</a></li>
</ul>
</li>
on window load, check to see if the window.location.href has a specific string
invoke the desired function
window.onload = function() {
if(window.location.href.includes('?getCustomers') {
getCustomers();
}else if(window.location.href.includes('?viewCustomer') {
viewCustomer();
}
}

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

Wrap each list array in a Tag

I am trying to get each Post lists wrapped in the href so it can be clicked on. Basically when I try to click on each Posts, it does not work until I hover my mouse close to the top of each posts before it works.
Below is my code and also an image of what I mean:
JS:
function getPosts(data) {
var $output = $('<ul class="posts" data-role="listview" data-filter="true">')
$.each(data.posts,function(i, val) {
$('<li><a href="#devotionpost" onclick="showPost(' + val.id + ')"</a>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).appendTo($output);
if ( i == 3 ) return false;
// return (postlimit-- > 1);
});
$('#postlist').empty().append($output);
}
function showPost(id) {
$('#mypost').html('<span class="img_spin">Loading post...</span>');
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var posts='';
posts += '<h3>' + data.post.title + '</h3>';
posts += data.post.content;
$('#mypost').html(posts);
});
}
Image:
If you look at the image, when i hover my mouse close to the top edge of the Post, then the URL at the bottom shows and that works but any where else does not work.
From looking at the Chrome Elements tab in this demo the JavaScript is generating invalid HTML because of mismatched closing elements.
Using an example posts of var posts = { "posts" : [ {"id":"1", "title":"lorem", "excerpt":"foo"}, {"id":"2", "title":"ipsum", "excerpt":"bar"} ] }
This '<li><a href="#devotionpost" onclick="showPost(' + val.id + ')"</a>' is resulting in the broken first child of the following <li>:
<li>
<a href="#devotionpost" onclick="showPost(1)" < a></a>
<h3>lorem</h3>
<p>foo</p>
</li>
Depending on exactly what you want to wrap in the anchor element, you could just build the post <li> like in this updated demo or see code below:
$.each(data.posts,function(i, val) {
$output.append('<li><h3>' + val.title + '</h3><p>' + val.excerpt + '</p></li>');
});
Or if you want to have a little less string concatenation, you could use .wrapInner()
$.each(data.posts,function(i, val) {
var $post = $('<li><h3>' + val.title + '</h3><p>' + val.excerpt + '</p></li>');
$post.wrapInner('');
$output.append($post);
});
Or keeping your .append() approach:
$.each(data.posts,function(i, val) {
var $post = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('');
$output.append($post);
});
Note: The string concatenation approach, combined with a single .append() is the best performing code.
By the looks of it, your lists are floating. You should use a clearfix technique to make "A" element box include the list. You also should know that by standard "A" elements are not allowed to contain block elements and as far as internet explorer 9 (didn't check in 10 or 11) "A" will not work the way you intended.
Possible workaround:
<div style="position:relative">
<ul>
<li></li>
<ul>
<a style="position:absolute;display:block;top:0;bottom:0;left:0:right:0;" href="#"></a>
<div>

Javascript - Dynamically added tabs not seen as tabs in Kendo panelbar

Ok, first off I read in an encrypted file as my DataSource, which is then converted to an XML String.
The data displays properly in my grids, except that the panels which are dynamically added to the panelbar does not seem to act as such as seen in this fiddle.
They are added to:
<ul id='panelbar'>
<li id='patDet' class='k-state-active'>
<span class='k-link k-state-selected'><input type='checkbox' id='cPatientDetails' /><label for='cPatientDetails'><a href='#' id='cbSelect'></a>Patient Detail</label></span>
<div id='patTab'></div>
</li>
</ul>
like so:
$("<li id = '"+ liID +"' class='k-item k-state-default' role='menuitem' aria-expanded='false' aria-hidden='true'><span class='k-link k-header'><input type='checkbox' id='c" + x + "' class='cbSelect' /><label for='c" + x + "'><a href='#' id='cbSelect''></a>" + liTitle + "</label></span></li>").appendTo("#panelbar");
$("<div id = 'gridGenerate" + x + "' width='400px;' aria-hidden='true'></div>").appendTo("#" + liID);
The reason for the span and link is so that styling can be used on my checkbox which can be found in this fiddle.
At first I used a hard coded DataSource, which worked perfectly, but when I switched over to fetching the data using a request, where all the data displays as it should, except for the panelbar.
This is what it looks like:
when only the first tab should be open. I created the panelbar like so:
$("#panelbar").kendoPanelBar(
{
expandMode: "single"
});
EDIT
I've made it now that the panelbar and grids are only created once the data is retreived and converted, but the issue remains.
Any idea why this is happening?
When KendoUI adds a tab, it does much more than just adding HTML tags. That's why you have methods for adding tabs on demand.
Instead of adding the HTML by hand try using:
var panelbar = $("#panelbar").data("kendoPanelBar");
panelbar.append([
{
text: "<label for='c" + x + "'>" +
"<a href='#' id='cbSelect''></a>" +
"" + liTitle + "" +
"</label>",
encoded: false,
content: "<div>text</div>"
}
]);
Click here to see it in JSFiddle.
Answer:
It seems like when I ask a question, it helps me to find the answer. Just found it.
I created the panelbar before adding the extra panels, so I just moved the:
$("#panelbar").kendoPanelBar(
{
expandMode: "single"
});
to the end of my method. The all the content is added, then I create the panelbar.

jQuery Mobile: How to navigate between dynamically generated pages

Using jQuery Mobile the code below does the following...
1) It generates menu items and adds them to the index page.
2) It creates actual pages for the menu items.
Now when I click on a menu item it does not seem to move to that page? I can see in the markup the pages exist with the correct id's.
This is what I have so far.
$.each(siteData["pages"], function(i,v) {
$.mobile.activePage.find('[data-role=content]').append('' +
'' + v["name"] + '').trigger('create');
// Prepare your page structure
var newPage = $("<div data-role='page' id=>" + v["id"] +
"<div data-role=header><a data-iconpos='left' data-icon='back' href='#' data-role='button' data-rel='back'>Back</a>" +
"<h1>Dynamic Page</h1>" +
"</div>" +
"<div data-role=content>Stuff here</div>" +
"</div>");
// Append the new page info pageContainer
newPage.appendTo($.mobile.pageContainer);
});
markup
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3></h3>
</div>
<div data-role="content" class="navlist"></div>
</div>
How do I navigate between dynamically generated pages?
Could someone give me an example using my code. Thank you.
Unfortunately you have few errors.
Take a look at my working example, it is made out of your code: http://jsfiddle.net/Gajotres/3kPTf/
$(document).on('pagebeforeshow', '#index', function(){
$.mobile.activePage.find('[data-role=content]').append('Second').trigger('create');
var newPage = $("<div data-role='page' id='second'><div data-role=header><a data-iconpos='left' data-icon='back' href='#' data-role='button' data-rel='back'>Back</a>" +
"<h1>Dynamic Page</h1>" +
"</div>" +
"<div data-role=content>Stuff here</div>" +
"</div>");
// Append the new page info pageContainer
newPage.appendTo($.mobile.pageContainer);
});
First error, close an a tag inside a button and give it a # tag.
Your dynamic page div is not closed properly

Categories