At first sorry if i have some typing errors english is not my main language but i try to do my best to explain it at my best.
I am working on a test app with a note database.
It works fine with adding and deleting but there is a small problem...
At the moment that i add a note (on edit.html) and want to go back to the index.html page it is not going back.
i am working with multiple data-page-role pages so each page has his own id.
The code that i use for the note database:
index.html Header:
$("#homePage").live('pageinit', function() {
init();
});
index.html data-page-role
<div data-role="page" id="homePage" data-add-back-btn="true" class="noteclass">
<!-- HEader -->
<div data-role="header" >
<h1>Notitie Database</h1>
</div>
<!-- Main content div -->
<div data-role="content" id="mainContent">
<ul data-role="listview" id="noteTitleList"></ul><br />
</div>
<div data-role="content">
Voeg notitie toe
</div>
<!-- Footer -->
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
Edit.html (here u can add/change/remove the notes)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div data-role="page" id="editPage">
<!-- HEader -->
<div data-role="header">
<h1>Write Note</h1>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#Delete').click(function() {
DeleteNote($('#noteId').val());
});
$('#addNote').click(function() {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data);
});
});
</script>
<div data-role="content">
<form id="editNoteForm" method="post">
<input type="hidden" name="noteId" id="noteId" value="">
<div data-role="fieldcontain">
<label for="noteTitle">Title</label>
<input type="text" name="noteTitle" id="noteTitle">
</div>
<div data-role="fieldcontain">
<label for="noteBody">Note</label>
<textarea name="noteBody" id="noteBody"></textarea>
</div>
<div data-role="fieldcontain">
<button id="addNote">Opslaan</button>
</div>
</form>
<button id="Delete">Verwijder</button>
</div>
Ga terug
<!-- Footer -->
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
</body>
</html>
And here is the backend code that i use for the note database
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
phoneready();
}
function setupTable(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
}
function getEntries() {
dbShell.transaction(function(tx)
{
tx.executeSql("select id,title,body, updated from notes order by id asc", dbErrorHandler, renderEntries)
}, function(){ alert ("Error getentries");
});
}
function renderEntries(tx,results){
if (results.rows.length == 0) {
$("#mainContent").html("<p>Je hebt nog geen notities.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[Geen Titel]";
dbShell.transaction(function(tx) {
if(note.id == "")
{
tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
}
else
{
tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}
}, function(){ alert ("Error savenote");},
function()
{
window.navigator.location("index.html#homePage");
});
}
function DeleteNote(id){
dbShell.transaction(
function(tx)
{
tx.executeSql('Delete FROM notes where id=' + id);
},
function(){ alert ("Error deletenote");},
function(err)
{
window.navigator.location("index.html#homePage");
});
}
function phoneready(){
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
setupTable();
}
function init(){
getEntries();
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pagebeforeshow", function() {
//get the location - it is a hash - got to be a better way
var loc = window.location.hash;
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
});
}, dbErrorHandler);
}
});
}
As u can see at saveNote and on deleteNote i call the function window.navigator.location("index.html#homePage");
I did this as far as i tried with $.mobile.changePage("index.html#homePage"); it will go back but then it won't run the init(); function at the header script.
I hope i explained it all correct and if there are any questions please let me know.
I will try then to do my best at explaining it.
edit:
More information:
At first thank you for your answer, i got multiple data-role-pages.
A extra example:
<div data-role="page" id="page5" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" >
<h1>Locatie</h1>
</div>
<!-- Main content div -->
<div data-role="content">
<p id="geolocation" onClick="onDeviceReady()">Op zoek naar uw locatie ...</p>
<img src="" id="map" width="100%" height="" />
<h4>Omgeving</h4>
<img src="" id="map2" width="100%" height="" />
</div>
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
You are trying to change page with deep link "index.html#homePage" .
JqueryMobile does not support that. When you pass a file, he will load ONLY the first page of that file.
This means that when you pass "index.html#homePage", he'll only consider the "index.html" and load the first page on that file.
I don't know it for sure, but if in your index.html file only have the "homePage", change function window.navigator.location to:
$.mobile.changePage("index.html")
And of course do the same for the anchor tag .
I use:
window.location = "#home";
Related
I created a code to display data from XML. I need to filter some data from XML and show in the page. Actually I need to show only three nodes in the page. When click the view all button, need to display other nodes. Please help me to implement the code.
Here is the code.
function showCD(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let TITLE = $(this).find("TITLE").text();
let ARTIST =$(this).find("ARTIST").text();
let COUNTRY = $(this).find("COUNTRY").text();
let COMPANY =$(this).find("COMPANY").text();
let html = `<div class="col-md-4">
<p>${TITLE}</p>
<p>${ARTIST}</p>
<p>${COUNTRY}</p>
<p>${COMPANY}</p>
</div>`;
$("#xmldata").append(html);
});
}
<div class="row" id="xmldata"></div>
<section>
<div class="container">
<input type="button" value="View All" id="myButton" class="reveal" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hidden'>
<div class="block">
<div class="row" id="xmldata"></div>
</div>
</div>
</div>
</section>
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
<CD category="new">
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD category="hide">
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CATALOG>
It is just like below image.
http://next.plnkr.co/edit/KgmzSWEaIOBRf54M?open=lib%2Fscript.js&preview
I have updated your code as per your requirement Demo
instead of 2 separate xmldata & xmldataall divs you can use only one div & hide all the children > 2 index.
$(document).ready(function(){
$.ajax({
type:"GET",
url:"test.xml",
dataType:"xml",
success:showCD
});
});
function showCD(xml){
xml = $(xml).children();
let i = 0;
$(xml).children().each(function () {
let TITLE = $(this).find("TITLE").text();
let ARTIST =$(this).find("ARTIST").text();
let COUNTRY = $(this).find("COUNTRY").text();
let COMPANY =$(this).find("COMPANY").text();
let html = `<div class="col-md-4">
<p>${TITLE}</p>
<p>${ARTIST}</p>
<p>${COUNTRY}</p>
<p>${COMPANY}</p>
</div>`;
i++;
if(i <= 3) {
$("#xmldata").append(html);
$("#xmldataall").append(html);
}
else{
$("#xmldataall").append(html);
}
});
}
$('#myButton1').click(function () {
var self = this;
change(self);
});
function change(el) {
if (el.value === "View All")
el.value = "Hide All";
else
el.value = "View All";
}
function toggler(divId) {
$("#" + divId).toggleClass("hide");
$("#xmldata").toggle();
}
function directLinkModal(hash) {
$(hash).modal('show');
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="row" id="xmldata"></div>
<section>
<div class="container">
<input type="button" value="View All" id="myButton1" class="reveal" style="float: right;" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hide'>
<div class="block">
<div class="row" id="xmldataall"></div>
</div>
</div>
</div>
</section>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</body>
</html>
I would like to print a bootstrap div.
It is properly displayed in web browser but when I click on the print button then at print preview, the elements are floating and are not properly displayed.
what should I do to solve this problem ?
Div which I want to print with following this style
What I get the output at printing time which I dont want see on school name at the top
Button which call the print function:
<button class="btn btn-default" onclick="printDiv('printableArea')"><i class="fa fa-print" aria-hidden="true" style=" font-size: 17px;"> Print</i></button>
Print Function:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
Div which i Want to print
<div class="container right-container col-md-6" id="printableArea" style="display:block;">
<span id="link7">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h3 id="school_title"><?php echo "$school_name";?> </h3>
<p><p>
<p style="font-size: 1.1em;" id="exam_title">Annual Examination [ 2015-2016 ] <p>
<div class="row">
<div class="col-md-4">
<div class="header-time-date-marks">
<span id="exam_time">Time: 12 AM - 2 PM</span>
<span id="exam_date">Date: 30/12/2016</span>
</div>
</div>
<div class="col-md-8 header-time-date-marks" style="text-align: right;padding-right: 36px;">
<span id="exam_marks">100 Marks</span>
</div>
</div>
</div>
</div>
<hr / id="line" style="margin-top: 13px;">
<div class="row q-question-type-style" id='question_section'>
</div>
</span>
</div>
Check this solution: It is working. The <div> is able to display for print.
Place your <script>-tag above the <html>-tag:
<script>
<html>
https://jsfiddle.net/6cz5br7m/
It's working, just try it on your Editor.
<!-- Your Jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!-- Another Jquery version, which will be compatible with PrintThis.js -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<!-- CDN/Reference To the pluggin PrintThis.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/printThis/1.15.0/printThis.js"
integrity="sha512-Fd3EQng6gZYBGzHbKd52pV76dXZZravPY7lxfg01nPx5mdekqS8kX4o1NfTtWiHqQyKhEGaReSf4BrtfKc+D5w=="
crossorigin="anonymous"></script>
<script type="text/javascript">
// important : to avoid conflict between the two version of Jquery
var j = jQuery.noConflict(true);
// define a function that you can call as an EventListener or whatever you want ...
function Print_Specific_Element() {
// the element's id must be unique ..
// you can't print multiple element, but can put them all in one div and give it an id, then you will be able to print them !
// use the 'j' alias to call PrintThis, with its compatible version of jquery
j('#specificElement').printThis({
importCSS: true, // to import the page css
importStyle: true, // to import <style>css here will be imported !</style> the stylesheets (bootstrap included !)
loadCSS: true, // to import style="The css writed Here will be imported !"
canvas: true // only if you Have image/Charts ...
});
}
$("#printBtn").click(Print_Specific_Element);
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- It's very important to include the attribute : media='all'-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" media='all'
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
#media print {
#page {
/* To give the user the possibility to choise between landscape and portrait printing format */
size: auto;
/* setting custom margin, so the date and the url can be displayed */
margin: 40px 10px 35px;
}
/* Here you can give a custom styling which will be applied only while printing */
a,
button#printBtn {
display: none;
}
}
</style>
</head>
<body>
<div class="container" id="Page">
<div>
this Element will not be printed
</div>
<div id="specificElement" class="bg-primary m-2 p-2 text-center rounded" style="border: 2px solid black;">
<div class="jumbotron">
<h1 class="display-3">
My custom content which I want to print
</h1>
<p class="lead">Another element</p>
<hr class="my-2">
<p>Nothing ... just another element </p>
<button id="printBtn" class="btn btn-success btn-sm shadow">
CLick Me !
<br>
(Dont worry I will not be printed)
</button>
</div>
</div>
</div>
</body>
</html>
Call this function: PrintElem('printableArea')
function PrintElem(elem){
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
var css = "";
var myStylesLocation = "${pageContext.request.contextPath}/ui/css/bootstrap.min.css";
$.ajax({
url: myStylesLocation,
type: "POST",
async: false
}).done(function(data){
css += data;
})
mywindow.document.write('<html><head><title></title>');
mywindow.document.write('<style type="text/css">'+css+' </style>');
// mywindow.document.write('<link rel="stylesheet" href="${pageContext.request.contextPath}/ui/css/bootstrap.min.css" type="text/css" media="print"/>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>' + document.title + '</h1>');
mywindow.document.write(document.getElementById(elem).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
You can try #media print in css.
Like bellow
In css
#media print
{
p.bodyText {font-family:georgia, times, serif;}
.noprint
{
display:none
}
}
In Html
<div class="noprint">
I dont want it on print
</div>
<br><br>
<div>
Prrintable Area
</div>
Fiddle
I was able to look for the section that was undesirably appearing in the print of the modal, and just hiding it, while using your print function:
print() {
let mainLayout = document.querySelector('app-main-layout') as HTMLDivElement;
mainLayout.style.display = 'none';
window.print();
mainLayout.style.display = 'unset';
}
And, make the buttons of my modal go away, by using this css:
#media print {
button.close {display:none !important;}
}
you just need to link your js script properly
<!DOCTYPE html>
<html>
<body>
<div class="container right-container col-md-6" id="printableArea" style="display:block;">
<span id="link7">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h3 id="school_title"><?php echo "$school_name";?> </h3>
<p><p>
<p style="font-size: 1.1em;" id="exam_title">Annual Examination [ 2015-2016 ] <p>
<div class="row">
<div class="col-md-4">
<div class="header-time-date-marks">
<span id="exam_time">Time: 12 AM - 2 PM</span>
<span id="exam_date">Date: 30/12/2016</span>
</div>
</div>
<div class="col-md-8 header-time-date-marks" style="text-align: right;padding-right: 36px;">
<span id="exam_marks">100 Marks</span>
</div>
</div>
</div>
</div>
<hr / id="line" style="margin-top: 13px;">
<div class="row q-question-type-style" id='question_section'>
</div>
</span>
</div>
<div> <h1>
asdads
</h1>
</div>
<button class="btn btn-default" onclick="printDiv('printableArea')"><i class="fa fa-print" aria-hidden="true" style=" font-size: 17px;"> Print</i></button>
<script>
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
</body>
</html>
I have TWO main questions that I really would have help with.
I have googled and searched for some day now without any help, but if you know any links that I maybe haven't watched or any site with help, then give me.
I would appreciated it, OR if you already have the code/sample code, would help :-)
I work with PhoneGap & JQuery Mobile right now, and the thing is this.
I have a 'textarea' there you write something, then a save button, what I want it to do is that when I press the save-button, the textvalue I wrote in the textarea would get saved in a listview in another page of the app. I have looked at "localstorage" but nothing works correctly.
(Also, if you write something in textarea and you press the cancel button, the text in the textarea should be deleted next time you go in to that page.)
The second question is:
When I press the save button, it should begin to count, in seconds, minutes, hours, days.
Think of it like this. I write "toothbrush" in the textarea and press save, now when I go to the listview-page, I can see it says toothbrush in the listview, beside the text it says 1m, 5m, 1h, it just update when it was last time I bought or changed the toothbrush, so next time I open the app, I can see "TOOTHBRUSH: 4Days, 16HRS, 52MINS AGO". In that way I can check when I bought something, or changed something.
This is my codes, both html & .js, what should I do so this mission will work.
Any suggestions, sites, or code you guys have that would help?
Thank you so much.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="save">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="cancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ol data-role="listview" id="orderedList" data-inset="true"></ol>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
and my almost empty -js code.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#add', function(){
$.mobile.navigate( "#page2", { transition : "slide", info: "info about the #bar hash" });
});
});
function save ()
{
var fieldValue = document.getElementById('textarea').value;
localStorage.setItem('content', orderedList);
}
EDIT:
Here is my new html & js file, after looked at your awesome code-example, but when I run it on my phone with phonegap, still, the save, cancel, the time and even the saved text will not show up.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea id="newItemText"></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#" data-transition="slide" id="btnSave">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="btnCancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="orderedList" data-inset="true">
</ul>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And the JS file.
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + timeAgo( (new Date(TheList[i].time).getTime())/1000) + ' ago<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});
function timeAgo(time){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var diff = (new Date() - new Date(time*1000)) / 1000;
if (diff < 5) return "now";
var i = 0;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit){
var diff = Math.floor(diff / unit.in_seconds);
return diff + " " + unit.name + (diff>1 ? "s" : "");
}
};
}
SOLUTION:
The JSFiddler code-example, the demo is perfect and are based on jQuery 1.9.1 & jQuery Mobile 1.3.0b1, I used 1.6.4 & 1.1.0.
After updating this two .js files, everything worked on PhoneGap!
Here is a DEMO
There are many questions within your problem, so I will probably not manage to answer all of them. To use localStorage with an array of 'tasks' you use JSON.stringify when saving and JSON.parse when retrieving.
So, each time page3 is displayed, you retrieve the current list of items from localStorage, create list items, empty the list and then append the created items :
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + TheList[i].time + '<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
When entering a new item, you want to store the text and the current time, so use an object. First get the current list from localStorage, then create the new item and add it to the list, finally save back to localStorage clear the textarea and navigate to page3. The cancel button just clears the textarea:
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I created a script to display the weather on my site, my problem when I execute it displays nothing.
this is my script :
<!DOCTYPE html>
<html>
<head>
<title>Weather API Test</title>
</head>
<body>
<script type="text/html" id="weather_tmpl">
<div class="weather_wrapper">
<div class="top_wrapper top_wrapper_e">
{{=day0}}
<div class="bt_control" id="meteo_controller">
<a href="javascript://">
<img src="arrow_open.png" id="meteo_trigger_img" width="27" height="17" alt="Arrow" />
</a>
</div>
</div>
<div class="bottom_wrapper" id="meteo_future_days">
<div class="next_days_wrapper">
<div class="day first">
{{=day1}}
<div class="clear"></div>
</div>
<div class="day">
{{=day2}}
<div class="clear"></div>
</div>
<div class="day last">
{{=day3}}
<div class="clear"></div>
</div>
</div>
<div class="bottom"></div>
</div>
</div>
</script>
<script type="text/html" id="detail_tmpl">
<div class="date">{{=date.weekday}},
<br />{{=date.day}} {{=monthname_short}}.</div>
<div class="temp">{{=high.celsius}}</div>
<div class="icon">
<img src="{{=icon_url}}" width="34" height="34" alt="icone" />
</div>
</script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="t.min.js"></script>
<script type='text/javascript'>
(function(){
var mainTpl = new t($('#weather_tmpl').html()),
detailTpl = new t($('#detail_tmpl').html());
$.getJSON('http://api.wunderground.com/api/2ea138a9dd52eabe/forecast/q/CA/San_Francisco.json')
.done(function(data){
var tplData = {};
$.each(data.forecast.simpleforecast.forecastday, function(index, day){
tplData['day'+index] = detailTpl.render(day);
});
$('body').append(mainTpl.render(tplData));
});
})();
</script>
<script>
var meteostatus = 0; // closed
$('#meteo_controller').click(function() {
if (meteostatus == 0) {
meteostatus = 1;
$('#meteo_future_days').fadeIn('slow');
$('#meteo_trigger_img').attr('src', $('#meteo_trigger_img').attr('src').replace('open', 'close'));
} else {
meteostatus = 0;
$('#meteo_future_days').fadeOut('slow');
$('#meteo_trigger_img').attr('src', $('#meteo_trigger_img').attr('src').replace('close', 'open'));
}
});
</script>
</body>
</html>
PS:
The data for the current day, and the forecast for the next 3 are in the array data.forecast.simpleforecast.forecastday.
I've used a templating library called t.js which you can find here
have a nice day
Replace the two of your scripts (the one with the id of library and the one with t.min.js) with:
<script src="https://github.com/jasonmoo/t.js/blob/master/t.min.js" />
<script type="https://github.com/jasonmoo/t.js/blob/master/template" id="test">
(function(){
var mainTpl = new t($('#weather_tmpl').html()),
detailTpl = new t($('#detail_tmpl').html());
$.getJSON('http://api.wunderground.com/api/2ea138a9dd52eabe/forecast/q/CA/San_Francisco.json')
.done(function(data){
var tplData = {};
$.each(data.forecast.simpleforecast.forecastday, function(index, day){
tplData['day'+index] = detailTpl.render(day);
});
$('body').append(mainTpl.render(tplData));
});
})();
var meteostatus = 0; // closed
$('#meteo_controller').click(function() {
if (meteostatus === 0) {
meteostatus = 1;
$('#meteo_future_days').fadeIn('slow');
$('#meteo_trigger_img').attr('src', $('#meteo_trigger_img').attr('src').replace('open', 'close'));
} else {
meteostatus = 0;
$('#meteo_future_days').fadeOut('slow');
$('#meteo_trigger_img').attr('src', $('#meteo_trigger_img').attr('src').replace('close', 'open'));
}
});
</script>
You tried to put a script src as a local path on your server, where the file is being hosted on github.
Also, there is a script error.
I can't get closed captioning to work on my video, I am pretty sure that I have a lot of the code that is required for getting it to work, and I am just not sure what I might be missing. I am also getting a message in the body, where it shows that the data-begin, and data-end are underlined green, and it says that Attribute data-begin is not a valid attribute of element span, I am not sure if thats the problem, and I may need to use another tag, and that can still get it to work. I am pretty new to html. Here is all my code
Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link type="text/css" href="skin/jplayer.blue.monday.css" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="javascripts/jquery.jplayer.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
m4v: "videos/sequence01mp4video.mp4",
poster: "http://www.jplayer.org/video/poster/Big_Buck_Bunny_Trailer_480x270.png"
});
},
swfPath: "/javascripts",
supplied: "m4v"
});
});
(function (_global) {
var captions = [];
var video;
var output;
var caplen;
window.addEventListener('load', function () {
output = document.createElement('div'); // JS is enabled, so insert a div to put the captions into
output.id = 'caption'; // it has an id of caption
video = document.querySelector('video'); // and it's after the first video element
video.parentNode.insertBefore(output, video.nextSibling);
getCaptions();
video.addEventListener('timeupdate', timeupdate, false);
}, false);
// function to populate the 'captions' array
function getCaptions() {
captions = []; // empty the captions array
var nodes = document.querySelectorAll('#transcript span');
var node = "";
var caption = "";
for (var i = 0, node; node = nodes[i]; i++) {
caption = {
'start': parseFloat(node.getAttribute('data-begin')), // get start time
'end': parseFloat(node.getAttribute('data-end')), // get end time
'text': node.textContent
};
captions.push(caption); // and all the captions into an array
}
caplen = captions.length;
}
function timeupdate() {
var now = video.currentTime; // how soon is now?
var text = "", cap = "";
for (var i = 0; i < caplen; i++) {
cap = captions[i];
if (now >= cap.start && now <= cap.end) { // is now within the times specified for this caption?
text = cap.text; // yes? then load it into a variable called text
break;
}
}
output.innerHTML = text; // and put contents of text into caption div
}
// hide transcript div when scripting is enabled
document.write('<style>#transcript{display:none}</style>');
})(this);
</script>
</head>
<body>
<div id="jp_container_1" class="jp-video ">
<div class="jp-type-single">
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
<div class="jp-gui">
<div class="jp-video-play">
play
</div>
<div id="transcript">
<span data-begin="0:00:00.380" data-end="0:00:03.670">hello, my name is rob carson environmental engineer with the</span>
<span data-begin="0:00:03.670" data-end="0:00:06.880">hello, my name is rob carson environmental engineer with the.</span>
</div>
<div class="jp-interface">
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-current-time"></div>
<div class="jp-duration"></div>
<div class="jp-controls-holder">
<ul class="jp-controls">
<li>play</li>
<li>pause</li>
<li>stop</li>
<li>mute</li>
<li>unmute</li>
<li>max volume</li>
</ul>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
<ul class="jp-toggles">
<li>full screen</li>
<li>restore screen</li>
<li>repeat</li>
<li>repeat off</li>
</ul>
</div>
<div class="jp-title">
<ul>
<li>Big Buck Bunny Trailer</li>
</ul>
</div>
</div>
</div>
<div class="jp-no-solution">
<span>Update Required</span>
To play the media you will need to either update your browser to a recent version or update your Flash plugin.
</div>
</div>
</div>
</body>
</html>