save text value to listview & start count the time - javascript

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

Related

How do I randomize images and audio while making sure to keep divs attatched in Javascript?

This is the site in question: driglight.com/Learn5.html
The purpose of this site is to click the audio and then choose which image you believe to be the correct representation of the note that was played.
I want to randomize the audio and answers every time the page is refreshed.
When the audio is randomized I need to make sure that the audio that is chosen has it's matching correct answer of an image also chosen and placed randomly among the answers. Also,when any possible answer image is clicked, a div will appear that says 'Good Job!' or 'incorrect'. So when the correct answer is randomized it will need to have the 'Good Job' div to follow it.
Here is the code in html:
<!DOCTYPE html>
<head>
<title>Learn</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/custom-styles.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/component.css">
<link rel="stylesheet" href="css/font-awesome-ie7.css">
<script src="js/stuff.js"></script>
<!-- <script src="js/Timhasnoinput.js"></script> -->
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
<div class="header-wrapper">
<div class="container">
<div class="row-fluid">
<div class="site-name">
<h1>Music Website</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="menu">
<div class="navbar">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="fw-icon-th-list"></i>
</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">Home</li>
<li>Learn</li>
<li>Contact</li>
</ul>
</div><!--/.nav-collapse -->
</div>
<div class="mini-menu">
<label>
<select class="selectnav">
<option value="#" selected="">Home</option>
<option value="#">→ Hello</option>
<option value="#">→ Something else here</option>
<option value="#">→ Another action</option>
<option value="#">→ Something else here</option>
<option value="#">About</option>
<option value="#">Learn</option>
<option value="#">Contact</option>
</select>
</label>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12 ">
<div class="main-caption">
<h1>Music Website</h1>
<h6>Learning Music</h6>
</div>
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12">
<div class="banner">
<div class="audiobuttonholder">
<div class="audioholder" style="padding-bottom:24px;">
<audio controls id="audio1">
hello
</audio>
</div>
<div class="buttonholder"; style="position: absolute; left: 10px; top: 40px;">
</div>
<div class = "numberPage">
Pg. 3 Trebble Cleff
</div>
<div class = "control">
<ul>
<div id="div1" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div1image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage1" style="height:200px;width:200px;
onclick="showDivOne()" />
</ul>
<ul>
<div id="div2" style="display:none; float: right; margin-right: 120px;" >
<img id=div2image imageC="incorrect.png" src="incorrect.png" />
</div>
<input type="image" id="myimage2" style="height:200px;width:200px; padding-
top:24px;" onclick="showDivTwo()"/>
</ul>
<ul>
<div id="div3" style="display:none; float: right; margin-right: 120px;
padding-top: 40px;" >
<img id=div3image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage3" style="height:200px;width:200px;padding-
top:24px;" onclick="showDivThree()"/>
</ul>
<ul>
<div id="div4" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div4image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage4" style="height:200px;width:200px;"
onclick="showDivFour()" />
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="featured-images">
<ul class="grid effect-8" id="grid">
<li>
<div class="block">
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</li>
</ul>
<div class="block-content">
<div class="user-info">
<h4>Home</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Learn</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Contact</h4>
<h6> </h6>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/masonry.pkgd.min.js"></script>
<script src="js/imagesloaded.js"></script>
<script src="js/classie.js"></script>
<script src="js/AnimOnScroll.js"></script>
<script>
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
} );
</script>
<script>
$('#myCarousel').carousel({
interval: 1800
});
</script>
</body>
</html>
And here is the code in Javascript:
function showDivFour() {
document.getElementById('div4').style.display = "block";
}
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
function showDivOne() {
document.getElementById('div1').style.display = "block";
}
function showDivTwo() {
document.getElementById('div2').style.display = "block";
}
function showDivThree() {
document.getElementById('div3').style.display = "block";
}
// THIS SHOULD BE THE BETTER ONE
var correctFileC = $('#div1image').attr("div_answer");
var correctFileC = $('#div2image').attr("div_answer");
var correctFileC = $('#div3image').attr("div_answer");
var correctFileC = $('#div4image').attr("div_answer");
var correctFile1 = $('#myimage1').attr("div_if");
var correctFile2 = $('#myimage2').attr("div_if");
var correctFile3 = $('#myimage3').attr("div_if");
var correctFile4 = $('#myimage4').attr("div_if");
var audio_1 = ["LowATrebbleCleffPianoVC.mp3","LowETrebbleCleffPianoVC.mp3",
"LowGTrebbleCleffPianoVC.mp3","MidBTrebbleCleffPianoVC.mp3",
"MidCTrebbleCleffPianoVC.mp3","MidDTrebbleCleffPianoVC.mp3"];
var rand_audio_1 =
audio_1[Math.floor(Math.random()*audio_1.length)].getElementByName.
(audioholder.innerHTML(rand_audio_1);
function div_if(){
if(audio_1[0]){
var R1 = ["myimage1","TrebbleCleffLowA.gif"],["myimage2","TrebbleCleffLowA.gif"],["myimage3","TrebbleCleffLowA.gif"],["myimage4","TrebbleCleffLowA.gif"];
if[R1(var i=0; i<R1.length;i++).length=4];
} else if(audio_1[1]){
var R2 = ["myimage1","LowE.gif"],["myimage2","LowE.gif"],["myimage3","LowE.gif"],["myimage4","LowE.gif"];
if[R2(var i=0; i<R2.length;i++).length=4];
do nothing
} else if(audio_1[2]){
var R3 = ["myimage1","LowG.gif"],["myimage2","LowG.gif"],["myimage3","LowG.gif"],["myimage4","LowG.gif"];
if[R3(var i=0; i<R3.length;i++).length=4];
do nothing
} else if(audio_1[3]){
var R4 = ["myimage1","MidB.gif"],["myimage2","MidB.gif"],["myimage3","MidB.gif"],["myimage4","MidB.gif"];
if[R4(var i=0; i<R4.length;i++).length=4];
do nothing
} else if(audio_1[4]){
var R5 = ["myimage1","MidC.gif"],["myimage2","MidC.gif"],["myimage3","MidC.gif"],["myimage4","MidC.gif"];
if[R5(var i=0; i<R5.length;i++).length=4];
do nothing
{ else if(audio_1[5]){
var R6 = ["myimage1","MidD.gif"],["myimage2","MidD.gif"],["myimage3","MidD.gif"],["myimage4","MidD.gif"];
if[R6(var i=0; i<R6.length;i++).length=4];
do nothing
} else if{
L1.Push(R);
} else if{
L1.Push(R1)
} else if{
L1.Push(R2)
} else if{
L1.Push(R3)
} else if{
L1.Push(R4)
}
function div_answer(){
if(R[0]){
document.getElementById(div1).innerHTML(divC);
divC.src='GoodJob.png'{
else if(R[1]){
document.getElementById(div2).innerHTML(divC);
divC.src='GoodJob.png'
}
else if(R[2]){
document.getElementById(div3).innerHTML(divC);
divC.src='GoodJob.png'
}
else {
document.getElementById(div4).innerHTML(divC);
divC.src='GoodJob.png'
}
}
}
I assume every audio fragment will have an image? So with that in mind, you create a random index to select an audio fragment (which you already do). Why don't you store that index in a variable and associate the image fragment with it?
Another option would be to create an object. So you make your array with audiofragments and then you initialize a new JS object, and assign the names of the images to 'properties' with your audiofragment as key. Like this:
var images = {};
images[audioname] = image-name;
***Do this for each audiofragment of course***
That way you can just ask the image from your images-object, using the property audioname.
When the page renders, place some value inside the attributes for the images or div:
<img id=myimage data-audio-file="xyz123.mp3" src="...." />
<div data-audio-file="xyz123.mp3" src="...." >My Content</div>
Read the attribute out when it's time to take some action:
var correctFile = $('#myimage').attr("data-audio-file");

on click generate anew tab using jquery

there is link on first tab and when i click on that link it should generate a new tab and focus should gone to that tab.there is a problem the tab is generated but the focus is not going to that tab can anybody help me plz.
<link rel="stylesheet" type="text/css" href="./compo.css"/>
<script type="text/javascript" src="./jquery-1.7.1.min.js" charset="utf-8"></script>
<script type="text/javascript" src="tabs-2.js" charset="utf-8"></script>
<title>"Tab sheet 2" demo — Component Library</title>
<script type="text/javascript">
function displaydetails() {
document.getElementById("tab2").style.display = "";
}
</script>
</head>
<body class="COMPO">
<!-- Wrapper -->
<div id="wrapper">
<!-- Container -->
<div id="container" class="resolution_800x600">
<!-- tabpanel_customer_data -->
<div id="tabpanel-demo" class="tab_panel_2 clear">
<ul id="tabpanel-liste" class="tab_menu clear">
<li id="tab1" class="tabpanel-tabbar-item tab_active">Tab 1</li>
<li id="tab2" class="tabpanel-tabbar-item" style="display:none"><a href="#content02" class="tabpanel-tabbar-link" >Tab 2</a></li>
</ul>
<!-- Tab_content 01 -->
<div id="content01" class="tab_panel_content_2">
<h3 class="title_n2" id="tab-1">tab 1</h3>
<div class="texts">
<p>
click me
</p>
</div>
<!-- /bloc_consultation -->
</div>
<!-- /Tab_content 01 -->
<!-- Tab_content 02 -->
<div id="content02" class="tab_panel_content_2">
<h3 class="title_n2" id="tab-2">tab 2</h3>
<div class="texts">
<p>
Content of the 2nd tab
</p>
</div>
<!-- /bloc_consultation -->
</div>
<!-- /Tab_content 02 -->
</div>
<!-- /tabpanel_customer_data -->
</div>
<!-- /Container -->
</div>
<!-- /Wrapper -->
js
var hideClass = "hide";
var tabClass = "tab_panel_2";
var activeClass = "tab_active";
var itemClass = "tabpanel-tabbar-item";
var linkClass = "tabpanel-tabbar-link";
var panelClass = "tab_panel_content_2";
var spanClass = "span_tab";
$(document).ready(function() {
$("."+panelClass).addClass(hideClass);
$("div."+tabClass+" ul li."+itemClass).each(function() {
var link = $(this).children("a");
$(this).append("<span class=\""+spanClass+"\">"+link.html()+"</span>");
$(this).children("span."+spanClass).hide();
});
$("div."+tabClass+" ul li."+activeClass+" a."+linkClass).each(function() {
$("#"+$(this).attr("href").replace("#","")).removeClass(hideClass);
$(this).hide();
$(this).siblings("span."+spanClass).show();
});
$("div."+tabClass+" ul li."+itemClass+" a."+linkClass).click(function() {
$(this).parents("div."+tabClass).children("."+panelClass).addClass(hideClass);
$(this).parents("li."+itemClass).siblings("li."+itemClass).children("span."+spanClass).hide();
$(this).parents("li."+itemClass).siblings("li."+itemClass).children("a."+linkClass).show();
$("#"+$(this).attr("href").replace("#","")).removeClass(hideClass);
$(this).hide();
$(this).siblings("span."+spanClass).show();
return false;
});
});
If this is your new tab try this:
$(this).parents("li."+itemClass).siblings("li."+itemClass).children("a."+linkClass).show().focus();

phonegap window.location not working with .html#page

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

Show and hide images with next previous button using Javascript

I have four divs, each div contain images and contents. one next and previous button. at a time only div will show. on click of next the second div have to be shown and first will hide. same upto fourth div. Need to use pure Javascript. No jquery or javascript plugins is allowed.... :(. Can anyone help me to do this?.
Thanks!
My html Code:
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="container">
<div id="theProduct">
<div id="slides"> <img src="img/prev.jpg" width="29" height="29" alt="Arrow Prev"> <img src="img/next.jpg" width="29" height="29" alt="Arrow Next">
<!-- Show/hide Div strating here -->
<div class="slides_container">
<div class="div1">
<div class="img1">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div2">
<div class="img2">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div3">
<div class="img3">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div4">
<div class="img4">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
</div>
<!-- Show/Hide Div ending here -->
</div>
<img src="img/example-frame.png" width="739" height="341" alt="Example Frame" id="frame"> </div>
</div>
</body>
</html>
Practical with this below
<style type="text/css" media="screen">
#container{position:relative;width:120px;height:120px;}
#container div{position:absolute;width:120px;height:120px;}
#box-red{background:red;}
#box-yellow{background:yellow;display:none;}
#box-green{background:green;display:none;}
#box-maroon{background:maroon;display:none;}
</style>
Javascipt
<script type="text/javascript">
var $c =0;
function next(){
var boxes = document.getElementsByClassName("box");
$c +=1;
if($c >= boxes.length) $c = 0;
for (var $i=0;$i<boxes.length;$i++){
boxes[$i].style.display = "none";
}
boxes[$c].style.display = "block";
return false;
}
function prev(){
var boxes = document.getElementsByClassName("box");
$c -=1;
if($c < 0) $c = (boxes.length-1);
for (var $i=0;$i<boxes.length;$i++){
boxes[$i].style.display = "none";
}
boxes[$c].style.display = "block";
return false;
}
</script>
HTML
<div id="container">
<div id="box-red" class="box">DIV1</div>
<div id="box-yellow" class="box">DIV2</div>
<div id="box-green" class="box">DIV3</div>
<div id="box-maroon" class="box">DIV4</div>
</div>
previous next
I think this is what you are loking for:
http://girlswhogeek.com/tutorials/2007/show-and-hide-elements-with-javascript
But you could put that in one function:
<script language="JavaScript">
function ShowHide(divId){
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
</script>
function toggleImage(forwrad){
var imageConainer = document.getElementByID(Your Parent div id);
var images = imageContainer.childNodes;
var showIndex = '';
for(var i=0; i<images.length;i++){
if(images[i].style.display == 'block'){
images[i].style.display == 'none';
if(forwrad){
showIndex = 1+1;
}
else{
showIndex = 1-1;
}
}
}
images[showIndex].style.display = true;
}
technically it's possible with pure CSS as well. with the :target pseudo class. but that would pollute your url with # tags. But you may actually want that.
Also Selectivizr is a good polyfill for old browsers

How do I make a direct call to a Menu item from the content?

I have this code, it works for a rotating menu that is obviously a ul> li> Menu.
What I would like to know is how to trigger (onClick, HRef, etc.) the function for a specific list item such as rot7.
I would like to click a line of text and fire the function, is this possible?
Example "Click here to go there" ,
Kinda like the old days -- {a href="some.html"}Click Here{/a} page loads.
In this case I want the text to open the 7th li> menu item using the form and function of the JQuery script.
There, clear as Mud.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Bridgett's Electrolysis</title>
<!-- Favorite Icon --><link rel="shortcut icon" href="images/beLogoColor3D.png" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><link rel="stylesheet" href="css/style.css" type="text/css" media="screen"/>
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<style>
*{
margin:0;
padding:0;
}
body{
font-family:Arial;
}
#content{
margin:150px auto 10px auto;
}
.reference{
clear:both;
width:800px;
margin:30px auto;
}
.reference p a{
text-transform:uppercase;
text-shadow:1px 1px 1px #fff;
color:#666;
text-decoration:none;
font-size:10px;
}
.reference p a:hover{
color:#333;
}
</style>
<script type="text/javascript">
// EDITED
$(function () {
$('#link6').click(function () {
$('#rotmenu li:nth-child(6)').click();
});
});
</script>
</head>
<body>
<div class="logoback">
<div id="logo">
<img src="images/beWebLogoColor3D.png" height="250">
</div>
</div>
<div id="content">
<div class="rotator">
<div class="myh">STOP TWEEZING UNWANTED HAIR.....FOREVER!!!</div>
<ul id="rotmenu">
<li>
Home
<div style="display:none;">
<div class="info_image">1.jpg</div>
<div class="info_heading">Relax</div>
<div class="info_description">
<div class="myh1">Eliminate Unwanted Hair</div><br />
<div class="col2"><img src="images/page1_img1.png" alt="" width="90%"></div>
<div class="col2">
<span class="myh2">Safe, Permanent Hair Removal<br />
<br />
Electrolysis is:</span><br />
<span class="myh3home">• Still the only true permanent hair removal method and the only
permanent treatment recognized by the FDA<br />
• An excellent solution for those discouraged by the unsuccessful results of temporary
hair removal methods<br />
• For everyone<br />
• The preferred treatment for combating folliculitis<br />
<br />
</span>
</div>
<div id="mycenter" class="myh2"><a id="link6" href="javascript:;">Book now to schedule your Complimentary Consultation</a>
</div>
</div>
</div>
</li>
<li>
News
<div style="display: none;">
<div class="info_image">2.jpg</div>
<div class="info_heading">The Scoop</div>
<div class="info_description">
<div class="col1">
<img src="images/page2_img1.jpg" alt="" />
<img src="images/appointment-request1.png" width="60%" alt="" />
<img src="images/page2_img3.jpg" alt="" />
</div>
<div class="col3">
<div class="mytabs">Open at our new Location!</div>
<span class="myh3">See our Location Section for a Map or Directions.</span><br /><br /><br /><br />
<div class="mytabs">Online Appointment Booking is Now Available!</div>
<span class="myh3">Go to our Appointments Section and schedule your appointment today.</span><br /><br /><br /><br />
<div class="mytabs">All New Equipment!</div>
<span class="myh3">The latest and greatest equipment has been installed to offer you the most comfortable Electrolysis experience.</span>
</div>
</div>
</div>
</li>
<li>
Services
<div style="display:none;">
<div class="info_image">3.jpg</div>
<div class="info_heading">Here to Serve You</div>
<div class="info_description">
<span class="mytabs">Electrolysis</span><br />
<span class="myh3">These are the areas that Electrolysis can be performed on.</span><br />
<img src="images/areas.png" / width="100%" height="350">
</div>
</div>
</li>
<li>
Location
<div style="display:none;">
<div class="info_image">4.jpg</div>
<div class="info_heading">Come and Visit</div>
<div class="info_description">
<span class="mytabs">1003 E. Broad St. Mansfield TX 76063</span>
<iframe width="100%" height="355px" seamless="seamless" frameborder="0" scrolling="no" marginheight="0"
marginwidth="0" src="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1003+E+Broad+St,+Mansfield,+TX&aq=2&oq=1003+E+Broad&sll=32.800447,-97.289319&sspn=0.966172,1.783905&t=m&ie=UTF8&hq=&hnear=1003+E+Broad+St,+Mansfield,+Texas+76063&ll=32.565228,-97.130527&spn=0.007568,0.013937&z=14&output=embed">
</iframe>
<br />
</div>
</div>
</li>
<li>
Contact Us
<div style="display:none;">
<div class="info_image">5.png</div>
<div class="info_heading">Get in Touch</div>
<div class="info_description">
<div class="col1">
<span class="mytabs">Contact Info:</span><br />
<span class="myh3">Bridgett's Electrolysis<br />
1003 E. Broad St<br />
Mansfield, TX. 76063<br />
Phone:(817)879-7817<br />
email: <a href="mailto:bridgettselectro#gmail.com?subject=Info Request from your site">
bridgettselectro#gmail.com</a><br />
</span>
</div>
<div class="col3">
</div>
</div>
</div>
</li>
<li>
FAQ
<div style="display:none;">
<div class="info_image">6.png</div>
<div class="info_heading">Electrolysis Questions?</div>
<div class="info_description">
<Iframe src="faq/faq.htm" width="100%" height="400" frameborder="0" marginheight="0"></Iframe>
</div>
</div>
</li>
<li>
Appointment
<div style="display:none;">
<div class="info_image">book.jpg</div>
<div class="info_heading">Book It</div>
<div class="info_description">
<Iframe src="webappt/index.php" width="100%" height="405" frameborder="0" marginheight="0"></Iframe>
</div>
</div>
</li>
<li>
FaceBook
<div style="display:none;">
<div class="info_image">like.png</div>
<div class="info_heading">Coment or Like Us</div>
<div class="info_description">
<div class="mycenter"><span class="myh2">Be Sure to Visit our FaceBook FanPage for deals and coupons!</span></div>
<div class="col2">
<div class="fb-like", data-href="http://www.bridgettselectro.com" data-send="false" data-width="450" data-show-faces="true" data-colorscheme="dark" data-font="arial"></div>
</div>
<div class="col2">
<div class="fb-comments" data-href="https://www.facebook.com/BridgettsElectrolysis?fref=ts" data-num-posts="10" data-width="350" data-colorscheme="dark"></div>
</div>
</div>
</div>
</li>
</ul>
<div id="rot1">
<img src="" width="800" height="300" class="bg" alt=""/>
<div class="heading">
<h1></h1>
</div>
<div class="description">
<p></p>
</div>
</div>
</div>
</div>
<!-- The JavaScript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script src="js/atooltip.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var current = 1;
var iterate = function () {
var i = parseInt(current + 1);
var lis = $('#rotmenu').children('li').size();
if (i > lis) i = 1;
display($('#rotmenu li:nth-child(' + i + ')'));
}
display($('#rotmenu li:first'));
var slidetime = setInterval(iterate, 3000000);
$('#rotmenu li').bind('click', function (e) {
clearTimeout(slidetime);
display($(this));
e.preventDefault();
});
function display(elem) {
var $this = elem;
var repeat = false;
if (current == parseInt($this.index() + 1))
repeat = true;
if (!repeat)
$this.parent().find('li:nth-child(' + current + ') a').stop(true, true).animate({ 'marginRight': '-20px' }, 300, function () {
$(this).animate({ 'opacity': '0.7' }, 700);
});
current = parseInt($this.index() + 1);
var elem = $('a', $this);
elem.stop(true, true).animate({ 'marginRight': '0px', 'opacity': '1.0' }, 300);
var info_elem = elem.next();
$('#rot1 .heading').animate({ 'left': '-420px' }, 500, 'easeOutCirc', function () {
$('h1', $(this)).html(info_elem.find('.info_heading').html());
$(this).animate({ 'left': '0px' }, 400, 'easeInOutQuad');
});
$('#rot1 .description').animate({ 'bottom': '-425px' }, 500, 'easeOutCirc', function () {
$('p', $(this)).html(info_elem.find('.info_description').html());
$(this).animate({ 'bottom': '0px' }, 400, 'easeInOutQuad');
})
$('#rot1').prepend(
$('<img/>', {
style: 'opacity:0',
className: 'bg'
}).load(
function () {
$(this).animate({ 'opacity': '1' }, 600);
$('#rot1 img:first').next().animate({ 'opacity': '0' }, 700, function () {
$(this).remove();
});
}
).attr('src', 'images/' + info_elem.find('.info_image').html()).attr('width', '1200').attr('height', '500')
);
}
});
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>
<a id="link6" href="javascript:;">click to open menu 6</a>
<script>
// EDITED
$(function() {
$('#link6').click(function(){
$('#rotmenu li:nth-child(6)').click();
});
});
</script>
EDIT:
The code above will not work because each time the menu is changing pages sets the container (.description) content with the original tags get upon initialization, so the page content including our a tag is overriden by a the original content which is same as previous one, but overrides the old one and that's why the click handler doesn't work - because it was set on an item which is overriden.
To not set the click handler each time when the menu changes the pages it should be bind into the link as simple as taht: <a onclick="$('#rotmenu li:nth-child(6)').click();" href="javascript:;">Book now to schedule your Complimentary Consultation</a>.
That's it - works fine.

Categories