how to give auto scroll to bottom when page before show - javascript

We developing chat application in that I am showing image,audio and text in the content div.
we have header div,content div,footer div.In content div adding new data dynamically i want show in bottom every time. if want see previous data i want scroll down to see. how to do that using jquery
$(document)
.on(
"pagebeforeshow",
"#chat",
function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
onFileSystemSuccess, fail);
load = true;
$('#opchat').empty();
$("#preopchat").empty();
$("#opchat1").empty();
var checkData = storageChat.getItem("chatdata");
if (JSON.parse(checkData) != null
&& JSON.parse(checkData) != undefined) {
storeChatData = JSON.parse(checkData).slice();
if (storeChatData.length > 10) {
var sliceChatData = [];
sliceChatData = storeChatData.slice(Math.max(
storeChatData.length - 10, 1));
for (var i = 0; i < sliceChatData.length; i++) {
if (sliceChatData[i] != undefined) {
if (sliceChatData[i].startsWith("file:///")) {
var filepath = sliceChatData[i].split(",")
if (filepath[1] == 'image/jpeg') {
var storedChat = '<img class="popphoto" id="profImgDashBrd" style="height: 70px; width: 70px;" src=\''
+ sliceChatData[i]
+ '\' >';
previewData(storedChat);
} else if (filepath[1] == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ sliceChatData[i]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
} else {
var filepath = storeChatData[i].split(",")
var storedChat ="<div class='right'>" + "<p>"
+ filepath[1] + "</p>" + "</div";
$("#opchat1").append(storedChat);
}
} else {
var storedChat ="<div class='left'>" + "<p>"
+ sliceChatData[i] + "</p>" + "</div>" + "<br>";
$("#opchat").append(storedChat);
}
}
}
} else {
for (var i = 0; i < storeChatData.length; i++) {
if (storeChatData[i] != undefined) {
if (storeChatData[i].startsWith("file:///")) {
var filepath = storeChatData[i].split(",")
if (filepath[1] == 'image/jpeg') {
var storedChat = '<img class="popphoto" style="height: 70px; width: 70px;" src=\''
+ filepath[0] + '\' >';
previewData(storedChat);
} else if (filepath[1] == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ filepath[0]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
} else {
var filepath = storeChatData[i].split(",");
var storedChat ="<div class='right'>" + "<p>"
+ filepath[1] + "</p>" + "</div";
$("#opqicchat1").append(storedChat);
}
} else {
var storedChat ="<div class='left'>" + "<p>"
+ storeChatData[i] + "</p>" + "</div>" + "<br>"
$("#opqicchat").append(storedChat);
}
}
}
}
}
});
function onFileSystemSuccess(fileSystem) {
folderName = "QLM"
var directoryEntry = fileSystem.root;
directoryEntry.getDirectory(folderName, {
create : true,
exclusive : false
}, gotDirEntry, fail)
}
function gotDirEntry(dirEntry) {
dirEntry.getFile("newFile.txt", {
create : true,
exclusive : false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
return true;
}
function fail() {
alert("error code");
}
// Text ,audio and images Display in chat
function previewData(data) {
var storedChat ="<div class='right'>" + "<p>" + data + "</p>" + "</div>" + "<br>";
$("#opqicchat1").append(storedChat);
}
// Text enter and submit
$(document).on('click', '#btnchatsend', function() {
var txtareaId = "txtarchat";
var txtareaVal = $("#" + txtareaId).val();
if (txtareaVal != null && txtareaVal != undefined && txtareaVal != "") {
storeChatData.push("file:///" + "," + txtareaVal);
storageChat.setItem("chatdata", JSON.stringify(storeChatData));
previewData(txtareaVal)
}
$("#" + txtareaId).val("");
$(textarea).val("");
});
// record audio and store
function startRecord() {
navigator.device.capture.captureAudio(captureSuccess, captureError, {
limit : 1
});
}
function captureSuccess(e) {
var audiofile = e[0].localURL;
var audiofilePath = e[0].fullPath;
audioname = audiofile.substr(audiofile.lastIndexOf('/') + 1);
filename = Date.now().toString() + audioname;
window.resolveLocalFileSystemURL(audiofile, copyFilePath, fail);
}
function captureError(e) {
alert(JSON.stringify(e));
}
function playRecAudio(url) {
if (play == true)
audioRecord = new Media(url, onAudioSuccess, onAudioError);
if (play == true) {
audioRecord.play();
play = false;
} else {
audioRecord.pause();
play = true;
}
}
function onAudioSuccess() {
}
function onAudioError() {
}
// capture image from camera
function getCapImg(source) {
navigator.camera.getPicture(onSavedDocURISuccess, onFails, {
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : source,
saveToPhotoAlbum : true
});
}
function imageGallery(source) {
navigator.camera.getPicture(onSavedDocURISuccess, onFail, {
quality : 30,
targetWidth : 600,
targetHeight : 600,
destinationType : destinationType.FILE_URI,
sourceType : source
});
}
function onSavedDocURISuccess(imageURI) {
filename = imageURI.substr(imageURI.lastIndexOf('/') + 1);
filename = Date.now().toString() + filename;
window.resolveLocalFileSystemURI(imageURI, copyFilePath, fail);
}
function copyFilePath(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(folderName, {
create : true,
exclusive : false
}, function(dir) {
fileEntry.copyTo(dir, filename, onCopySuccess, fail);
}, fail);
}, fail);
}
function onCopySuccess(entry) {
entry
.file(function(file) {
storeChatData.push(entry.toURL() + "," + file.type);
storageChat.setItem("chatdata", JSON
.stringify(storeChatData));
var getimageData = storageQlmChat.getItem("chatdata");
var arrayformate = JSON.parse(getimageData);
$
.each(
arrayformate,
function(index, value) {
var imagepath = value.split(",")
if (index == arrayformate.length - 1) {
if (file.type == 'image/jpeg') {
var storedChat = '<img class="popphoto" style="height: 70px; width: 70px;" src=\''
+ imagepath[0] + '\' >';
previewData(storedChat);
} else if (file.type == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ imagepath[0]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
}
}
});
});
}
function fail(error) {
alert("error" + error.code);
}
.left {
margin-top:10px;
position: relative;
background: aqua;
text-align: left;
min-width: 85%;
padding: 15px 10px;
border-radius: 6px;
border: 1px solid #ccc;
float: left;
left: 8%;
}
.left::before {
content: '';
position: absolute;
visibility: visible;
top: -1px;
left: -10px;
border: 10px solid transparent;
border-top: 10px solid #ccc;
}
.left::after {
content: '';
position: absolute;
visibility: visible;
top: 0px;
left: -8px;
border: 10px solid transparent;
border-top: 10px solid aqua;
clear: both;
}
.right {
position: relative;
background: white;
text-align: right;
min-width: 85%;
padding: 10px 15px;
border-radius: 6px;
border: 1px solid #ccc;
float: right;
right: 5%;
margin-top: 10px;
}
.right::before {
content: '';
position: absolute;
visibility: visible;
top: -1px;
right: -10px;
border: 10px solid transparent;
border-top: 10px solid #ccc;
}
.right::after {
content: '';
position: absolute;
visibility: visible;
top: 0px;
right: -8px;
border: 10px solid transparent;
border-top: 10px solid white;
clear: both;
}
<div class="headerDiv" data-role="header"
id="hdrIdchat" data-position="fixed" data-tap-toggle="false" data-transition="none">
<a class="ui-btn ui-icon-arrow-l ui-btn-icon-left" onClick="navBack()"></a>
<h1 id="lblHdrchat">Chat</h1>
<div data-tap-toggle="false" data-transition="none" style="border-top:1px solid white;width: 100%; text-align: center; display: inline-flex;">
<div style="width: 100%; padding: 10px;">
<img alt="" src="images/vo.png" onclick="startRecord()" style="height: 25px;">
</div>
<div style="width: 100%; padding: 10px">
<img alt="" src="images/imcht.png" onClick="imageGallery(pictureSource.PHOTOLIBRARY)" style="height: 25px;">
</div>
<div style="width: 100%; padding: 10px">
<img alt="" src="images/camcht.png" onclick="getCapImg(navigator.camera.PictureSourceType.CAMERA);" style="height: 25px;">
</div>
</div>
</div>
<div data-role="content">
<div onclick="preChatData()">
<p align="center"></p>
</div>
<div id="example">
<div id="preopqicchat"></div>
<div id="opqicchat" ></div>
<div id="opqicchat1" ></div>
</div>
</div>
<div data-role="footer" data-position="fixed" id="chatfooter"
style="background: transparent; border: none;" data-tap-toggle="false" data-transition="none">
<div style="display: inline-flex; width: 100%;">
<div style="width: 100%">
<textarea autofocus="autofocus" id="txtarchat"></textarea>
</div>
<div>
<button data-role="button" class="ui-btn ui-btn-b"
id="btnchatsend" style="width: 100% !Important;">SEND</button>
</div>
</div>
</div>
Actual Result
Expected Result

Have a look at this demo
header,
footer {
flex: 0 0 auto;
}
main grows in height with the content. The number '1' in the flex shorthand tells how much free space in the container is allocated to the element. In our case, main is given the free space. The auto part of the value is the default size of the flex element. We want auto for all flex children.
main {
flex: 1 0 auto;
...
}
The footer will always be beneath the content, no matter what.
Footer starts at bottom
Footer gets pushed down by content
http://codepen.io/antibland/pen/WwKRBx

Related

Array wont update when i JSON.stringify it

I have this code below that is able to transfer the array value to another array when i click on it. For Example, when i click on lime it will move into my Green Array The problem is after i JSON.stringify my Green Array it doesn't show the updated value.
So this is the before i add in a value my green array has 5 values.
And this is after I add in a value to my green array as you can see after I move the value in my array count increases but I don't know why when i stringify the array, it doesn't have the value I added in already I want to stringify it because I want to send the updated data to a server. Is there any reason why this is happening ?
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
var randomFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = randomFruits;
function redraw() {
var combineString = '';
$.each(red[key], function(index) {
combineString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.combineclass').html(combineString);
$.each(green[key2], function(index) {
combineString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.combineclass').html(combineString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data) {
if (fruits[i].type === "1") {
red[key].push(data);
} else {
green[key2].push(data);
}
}
}
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data2) {
if (fruits[i].type === "1") {
k2 = Object.keys(red).find(k => red[k].indexOf(data2) >= 0);
index2 = red[k2].indexOf(data2);
red[k2].splice(index2, 1);
} else {
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0);
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
}
}
}
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').prepend('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
var testing = JSON.stringify(green);
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.randompill:after{
content: "\002B";
float: left;
width:16px;
}
.new-green-fruit:after{
content: "\292B";
float: left;
width:16px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Total Fruits</h3>
<div id="combineid" class="combineclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Random Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
It is working fine as expected. Look into the code base properly may be you are missing something.
var greenFruits = ["Watermelon", "Durian", "Avacado", "Lime", "Honeydew"];
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));
greenFruits.push("Guava");
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));

Cannot get button to switch between Fahrenheit and Celsius

I'm working on the freeCodeCamp "Show the local weather" project. I have almost everything working except I cannot seem to get the switch to toggle between Fahrenheit and Celsius to work properly. It's a very basic page for showing the weather and I want the user to be able to switch between Fahrenheit and Celsius by clicking on the tags and then the page will update with the new temperature. Currently, when I click on the 'C' tag it will display the correct temperature for a brief moment, but then quickly switch back to Fahrenheit. Any help would be greatly appreciated. Here is the link to the page: https://codepen.io/spencerj171/full/yzmmvR/
Thanks to everyone in advance!
HTML
<body>
<div class="container weather">
<div id="location"></div>
<div class="row">
<div class="col-lg-6">
<br><br>
<span class="ftemp" id="currentTemp"></span>
<span id="forc"> F | C</span>
<div>
<span id="icon"></span>
<span id="description"></span>
</div>
<span class="ftemp" id="lowTemp"></span>
<span class="ftemp" id="highTemp"></span>
<div id="humidity"></div>
</div>
<div class="col-lg-6">
<div id="map"></div>
</div>
</div>
</body>
CSS
body{
background-color: rgb(152, 157, 165);
color: black;
}
.switch{
border: none;
background-color: rgb(255, 255, 255);
text-decoration: none;
}
.weather{
text-align: center;
margin-top: 100px;
background-color: rgb(255, 255, 255);
border-radius: 5px;
padding: 50px 50px 50px 50px;
width: 50%;
height: auto;
position: relative;
}
#location{
font-size: 2em;
padding-bottom: .5em;
}
#currentTemp{
font-size: 1.5em;
display: inline-block;
}
#forc{
color: black;
display: inline-block;
font-size: 1em;
}
#icon{
width: 100%;
height: auto;
}
#description{
display: inline-block;
}
#lowTemp{
display: inline-block;
padding-right: 10px;
}
#highTemp{
display: inline-block;
}
#humidity{
}
#map{
width: 100%;;
height: 300px;
margin: auto;
}
a.switch{
text-decoration: none;
color: black;
}
a:hover{
color: rgb(0, 182, 255);
}
JavaScript
var url = "https://api.openweathermap.org/data/2.5/weather?q=cleveland&appid=d32fada3b37530ca403693700ae6c134";
var gurl = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCrBes2R9nOEvbMHMoJ4oCTzSNGaOD6eQc&callback=initMap";
var degree = '<span id="forc"> F | C</span>';
var apiOpen = "d32fada3b37530ca403693700ae6c134";
var map;
var tempSwitch = false;
$(document).ready(function(){
getLocation();
});
//Get location of user
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeather();
initMap();
});
} else{
alert("Please allow location services.")
}
}
//Retrieve weather
function getWeather(){
data = $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
success: function(json){
current = fahrenheit(json.main.temp);
low = fahrenheit(json.main.temp_min);
high = fahrenheit(json.main.temp_max);
$("#location").html("<div id='location'>" + json.name + " Weather</div>");
$("#currentTemp").html("<span class='ftemp' id='currentTemp'>" + current + "°" + "</span>");
$("#icon").html("<span id='icon'><img src='https://openweathermap.org/img/w/" + json.weather[0].icon + ".png'></span>");
$("#description").html("<span id='description'>" + json.weather[0].description.toUpperCase()) +"</span>";
$("#lowTemp").html("<span class='ftemp' id='lowTemp'>↓ " + low + "° " + "</span>");
$("#highTemp").html("<span class='ftemp' id='highTemp'>↑ " + high + "° " + "</span>");
$("#humidity").html("<div id='humidity'>Humidity: " + json.main.humidity + "%</div>");
}
});
switchTemp();
}
//Create Map
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.505493, lng: -81.681290},
zoom: 10
});
}
//Convert temperature
function fahrenheit(kel){
var f = Math.floor(9/5 * (kel - 273) + 32);
return f;
}
function fahr(c){
var fahr = Math.floor( c * 1.8 + 32);
return fahr;
}
function celsius(f){
var c = Math.floor((f - 32) * 5/9);
return c;
}
//Switch temperature
function switchTemp(){
$("#c").on("click", function(){
if(tempSwitch === false){
$("#currentTemp").html("<span id='currentTemp'>" + celsius(current) + "°" + "</span>");
$("#lowTemp").html("<span id='lowTemp'>↓ " + celsius(low) + "° " + "</span>");
$("#highTemp").html("<spanid='highTemp'>↑ " + celsius(high) + "° " + "</span>");
tempSwitch === true;
}
});
$("#f").on("click", function(){
if(tempSwitch === true){
$("#currentTemp").html("<span id='currentTemp'>" + fahr(current) + "°" + "</span>");
$("#lowTemp").html("<span id='lowTemp'>↓ " + fahr(low) + "° " + "</span>");
$("#highTemp").html("<spanid='highTemp'>↑ " + fahr(high) + "° " + "</span>");
tempSwitch === false;
}
});
}
There was 2 problems in your code:
You C and F is a link, so when you click it makes a page refress since you have nothing in href="". either use href="#" or e.preventDefault(); as in the example just below:
$("#f").on("click", function(e){
e.preventDefault();
});
You use === to set tempSwitch as in tempSwitch === false but you need to use only one = as in tempSwitch = false
DEMO

javascript background image change using array

I am not exprienced javascript programmer so I try to play with javascript. I am trying to make a slideshow by clicking on a button. Function I am trying to make a function with array that holds the names of all the images and changing the background-image according to the index of the array. I did only this part of function yet and I cant get what is wrong.
function change(lol){
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(change === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
}
middle {
width:1262px;
height:550px;
background-color: white;
margin-left: -7px;
}
#vvvmiddle {
width:700;
height:400;
background-image:url('veni1.jpg');
margin: 20px 0px 0px 310px;
float:left;
}
#sipka {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px 410px 0px 0px;
}
#sipkatext {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 10px;
padding-top: 1px;
}
#sipkaurl {
text-decoration: none;
}
#sipka:hover {
background-color: #3399FF;
}
#sipka2:hover {
background-color: #3399FF;
}
#sipka2 {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px -100px 0px 0px;
}
#sipkatext2 {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 13px;
padding-top: 1px;
}
<div id="middle">
<div id="vvvmiddle">
<div id="sipka" onclick="change('left')">
<div id="sipkatext">
<</div>
</div>
<div id="sipka2" onclick="change('right')">
<div id="sipkatext2">></div>
</div>
</div>
</div>
A possible solution may be this one:
var img = ["img1.png", "img2.png", "img3.png"];
var len = img.length;
var url = 'Some url...';
var current=0;
var middle = document.getElementById("vvvmiddle");
middle.style.backgroundImage = "url(" + url + img[current] + ")";
function change(dir){
if(dir == "right" && current < len-1){
current++;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
} else if(dir == "left" && current > 0){
current--;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
}
}
See it in action, check here jsfiddle.
You can try with that:
function change(lol) {
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(lol === "right"){
index = (index + 1) % img.length;
} else {
index = (index + img.length - 1) % img.length;
}
middle.style.backgroundImage = img[index];
}
You are checking wrong variable in condition, it should be lol, not change:
if(lol === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
Also you should handle "last image" case like Nicolas suggests.

PhoneGap javascript reference issue

In my PhoneGap Eclipse project I am using jQuery for visual effects by referencing jQuery libraries:
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
and I am also making remote domain requests in order to display some information from the remote server.
1: When I make requests to multiple servers, I get an error saying:
DroidGap: TIMEOUT ERROR! - calling webViewClient
I read that I must alter my Phonegaps whitelist by doing:
<phonegap>
<access origin="\*\" />
</phonegap>
Source: GitHub call-back
But I get some error, so I have decided to approach same results from the different ways:
2: <script type="text/javascript" src="file:///android_asset/js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
Why? - because i would like to avoid getting errors with multiple-domain requests
In these cases I get an error
SyntaxError: Parse error at file:///... in logcat
I have no idea why this is happening, because the specified file location supposed to be right in both cases.
So my questions are:
Why I cannot include .js file in this way?
Which solution I should continue trying to approach (1 or 2)?
<html>
<head>
<title></title>
<script src="phonegap-1.3.0.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0.css" />
<script type="text/javascript" src="jquery.mobile-1.0.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<!--
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="lib/touch/resources/css/sencha-touch.css" type="text/css">
<script type="text/javascript" src="lib/touch/sencha-touch.js"></script>
<!-- <script type="text/javascript" src="lib/touch/index.js"></script> -->
<script>
var alreadyrunflag = 0 //flag to indicate whether target function has already been run
var url = "http://www.norwegian.no/";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
//on page loaded
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function() {
//alreadyrunflag = 1;
initGet(url);
}, false)
else if (document.all && !window.opera) {
//page load error?
}
function applyChangeEvent() {
//on selection changed
var selectDepart = document.getElementById("depart");
var selectArrive = document.getElementById("arrive");
selectDepart.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
selectArrive.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
}
function initGet(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
getObjs(request.responseText);
}
}
}
request.send();
}
function get(url, month) {
//alert(month);
url += "?D_City="
+ document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value;
url += "&A_City="
+ document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value;
url += "&TripType=1";
url += "&D_Day=1";
url += "&D_Month=" + getMonth(month);
/* url += "&R_Day=1";
url += "&R_Month=201201"; */
url += "&AdultCount=1";
url += "&ChildCount=0";
url += "&InfantCount=0";
//alert(url);
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
parse(request.responseText, month);
}
}
}
request.send();
}
function getMonth(month) {
//alert(month.toString.length + " | " + month);
if (month.toString().length == 1) {
var tempMonth = "0" + month.toString();
//alert(tempMonth);
return year.toString() + tempMonth;
} else
return year.toString() + month;
}
function getSimpleMonth() {
return month;
}
function getObjs(mainPageHtml) {
var mainDoc = (new DOMParser()).parseFromString(mainPageHtml,
"application/xhtml+xml");
var select = mainDoc.getElementsByTagName("select")[1];
var options = select.getElementsByTagName("option");
var citiesArray = [];
for ( var i = 0; i < options.length; i++) {
cityObj = new Object();
cityObj.name = options[i].text;
cityObj.value = options[i].value;
citiesArray.push(cityObj);
}
for ( var city = 0; city < citiesArray.length; city++) {
document.getElementById("depart").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
document.getElementById("arrive").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
}
applyChangeEvent();
}
function parse(html, id) {
var pricesArray = [];
//alert(id);
var resultDoc = (new DOMParser()).parseFromString(html,
"application/xhtml+xml");
var divs = resultDoc.getElementsByTagName("table");
for ( var div = 0; div < divs.length; div++) {
if (divs[div].className == "fareCalendarTable") {
//alert("found!");
// TODO: find out how many to open!!
document.getElementById(id).style.display = "block";
document.getElementById("nav_").style.display = "block";
var table = resultDoc.getElementsByTagName("table")[div];
var divs = table.getElementsByTagName("div");
//var tbodyTrs = tbody.getElementsByTagName("tr");
//alert(document.getElementById("month-one").innerHTML);
for ( var price = 0; price < divs.length; price++) {
if (divs[price].title != "") {
/* document.getElementById("month-one-results").innerHTML += divs[price].id
.replace("OutboundFareCal", "")
+ " : " + divs[price].title + "<br>"; */
priceObj = new Object();
priceObj.date = divs[price].id.replace(
"OutboundFareCal", "");
priceObj.price = divs[price].title.replace(" NOK", "");
priceObj.price.replace(/\s/g, '');
pricesArray.push(priceObj);
}
}
/* pricesArray.sort(function sortNumber(a, b) {
return parseInt(b) - parseInt(a);
}); */
for ( var priceUnit = 0; priceUnit < pricesArray.length; priceUnit++) {
document.getElementById("month-results-" + id).innerHTML += "<table><tr><td>"
+ pricesArray[priceUnit].date
+ "</td><td>"
+ pricesArray[priceUnit].price
+ "</td></tr></table>";
}
}
document.getElementById("depart").disabled = "disabled";
document.getElementById("arrive").disabled = "disabled";
}
// document.getElementById("results").innerHTML = bodybox.item(0).innerHTML;
//holy grail!
var month = document.getElementById("month-" + id);
var spans = month.getElementsByTagName("span");
for ( var span = 0; span < spans.length; span++) {
if (spans[span].className == "ui-btn-text") {
spans[span].innerHTML += "<p>" + getCheapest(pricesArray)
+ "</p>";
}
}
}
function getCheapest(pricesArray) {
pricesArray.sort(sort);
return pricesArray[1].price;
}
function sort(a, b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function restart() {
window.location.reload();
return false;
document.getElementById("depart").removeAttribute("disabled");
document.getElementById("arrive").removeAttribute("disabled");
}
</script>
<style>
body {
display: block;
padding: 20px;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
}
div#content {
margin-left: auto;
margin-right: auto;
background: #fff;
height: 100%;
-webkit-border-bottom-left-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
display: block;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
background-image:
url(http://www.norwegian.no/Global/backgrounds/background_no.gif);
background-repeat: repeat-x;
background-repeat-x: repeat;
background-repeat-y: no-repeat;
background-position-x: 0%;
background-position-y: 0%;
width: 100%;
padding-top: 20px;
padding-bottom: 30px;
}
div#navigation {
margin-left: auto;
margin-right: auto;
padding: 20px;
position: block;
width: 80%;
background: #CCCC00;
-webkit-border-radius: 8px;
}
select {
position: block;
width: 100%;
text-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<div id="nav_" data-role="header" data-position="inline" data-theme="e"
style="display: none;">
<a href="#" data-icon="back" data-theme="c"
onClick="window.location.reload();return false;">Start</a>
<h1>Ticket Prices</h1>
</div>
<div id="content">
<div id="navigation">
Fra/From: <select id="depart">
</select> Til/To: <select id="arrive">
</select>
</div>
<div data-role="collapsible" id="1"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-1">January</h3>
<p id="month-results-1"></p>
</div>
<div data-role="collapsible" id="2"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-2">February</h3>
<p id="month-results-2"></p>
</div>
<div data-role="collapsible" id="3"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-3">March</h3>
<p id="month-results-3"></p>
</div>
<div data-role="collapsible" id="4"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-4">April</h3>
<p id="month-results-4"></p>
</div>
<div data-role="collapsible" id="5"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-5">May</h3>
<p id="month-results-5"></p>
</div>
<div data-role="collapsible" id="6"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-6">June</h3>
<p id="month-results-6"></p>
</div>
<div data-role="collapsible" id="7"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-7">July</h3>
<p id="month-results-7"></p>
</div>
<div data-role="collapsible" id="8"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-8">August</h3>
<p id="month-results-8"></p>
</div>
<div data-role="collapsible" id="9"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-9">September</h3>
<p id="month-results-9"></p>
</div>
<div data-role="collapsible" id="10"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-10">October</h3>
<p id="month-results-10"></p>
</div>
<div data-role="collapsible" id="11"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-11">November</h3>
<p id="month-results-11"></p>
</div>
<div data-role="collapsible" id="12"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-12">December</h3>
<p id="month-results-12"></p>
</div>
</div>
<!-- <div id="results"></div> -->
</body>
</html>
If your directory structure is assets/www/js/jquery.js use :
<script type="text/javascript" src="js/jquery.js"></script>

Accordian Element Height Issue

I have implemented 2 types of Accordians for my application- 1 Column and 2 Column
Im having a problem with the Static Height for the 1 Column Accordian. And I've been trying to modify the JavaScript all day but cant seem to get it to work.
The Heights should be dynamic in Height depending upon the amount data, however as you can see the Height is fixed, and some of the data is getting cut off:
http://www.davincispainting.com/whydavincis.aspx
The other 2 Column Accordian has almost the same JavaScript as the 1 Column Accordian, however the Height is dynanmic depending on how much data there is:
http://www.davincispainting.com/glossary.aspx
I would provide a Fiddle however the Data is now dynamic:
Here is the JavaScript for the problem Accordian:
<script type="text/javascript">
$.fn.accordion = function () {
return this.each(function () {
$container = $('#mid-featureleft-client');
$container.find("dt").each(function () {
var $header = $(this);
var $selected = $header.next();
$header.click(function () {
$('.active').removeClass('active');
$(this).addClass('active');
if ($selected.is(":visible")) {
$selected.animate({
height: 0
}, {
duration: 300,
complete: function () {
$(this).hide();
}
});
} else {
$unselected = $container.find("dd:visible");
$selected.show();
var newHeight = heights[$selected.attr("id")];
var oldHeight = heights[$unselected.attr("id")];
$('<div>').animate({
height: 1
}, {
duration: 300,
step: function (now) {
var stepSelectedHeight = Math.round(newHeight * now);
$selected.height(stepSelectedHeight);
$unselected.height(oldHeight + Math.round((newHeight - oldHeight) * now) - Math.round(newHeight * now));
},
complete: function () {
$unselected.hide().css({
height: 0
});
}
});
}
return false;
});
});
// Iterate over panels, save heights, hide all.
var heights = new Object();
$container.find("dd").each(function () {
$this = $(this);
$this.css("overflow", "hidden");
heights[$this.attr("id")] = $this.height();
$this.hide().css({
height: 0
});
});
});
};
$(document).ready(function () {
$.getJSON('FaqsJson.ashx?factType=2', function (datas) {
var str_one = "";
str_one = "<dl>"
$.each(datas, function () {
str_one += "<dt class=\"glossquestion\">" + this['Question'] + "</dt>";
str_one += "<dd class=\"glossanswer\" style=\"-webkit-margin-start:0px\"><div class=\"answerbox\">" + this['Answer'] + "</div></dd>";
});
str_one += "</dl>";
$("#glossary_first").html(str_one);
$("#mid-featureleft-client").accordion();
});
});
</script>
Here is the relevent HTML:
<div id="mid-feature-client">
<div id="mid-featureleft-client">
<div id="glossary_first" class="controlbox">
<br /><br />
</div>
<div style="clear: both;">
</div>
</div>
</div>
Here is the relevent css:
#mid-featureleft-client .controlbox {
width:546px;
padding:3px 0 0 6px;
position:relative;
/*background-color:green;*/
}
#mid-featureleft-client .glossarycontrolbox {
width:260px;
padding:3px 0 0 6px;
position:relative;
float:left;
/*background-color:blue;*/
}
.question-clicked {
background-color: #CCCCCC;
color: #0C2A55;
/*margin-top: 10px;*/
/*padding: 2px 5px 0;*/
}
.questionLink-clicked {
color: #0C2A55;
font-size: 1.2em;
font-weight: bold;
}
.answerbox {
padding: 3px 5px 3px 5px;
}
.questionLink {
color: #0C2A55;
font-size: 1.2em;
font-weight: bold;
}
.glossquestion {
padding: 0 5px 4px 0;
}
.glossanswer {
background-color: #F9FBFC;
display: none;
}
#accordion .handle {
width: 260px;
height: 30px;
background-color: orange;
}
#accordion .section {
width: 260px;
height: 445px;
background-color: #a9a9a9;
overflow: hidden;
position: relative;
}
dt {
/*background-color: #ccc;*/
}
dd {
/*height: 30px;*/
}
.active {
background: #a9a9a9;
}
The problem is with the way you're storing the heights, a bit after this comment:
// Iterate over panels, save heights, hide all.
Specifically, this line:
heights[$this.attr("id")] = $this.height();
Your dd elements don't have an id, so on each iteration of the loop, heights[''] is being set to the height of the current dd.
You should be able to fix it by changing this:
$.each(datas, function () {
str_one += "<dt class=\"glossquestion\">" + this['Question'] + "</dt>";
str_one += "<dd class=\"glossanswer\" style=\"-webkit-margin-start:0px\"><div class=\"answerbox\">" + this['Answer'] + "</div></dd>";
});
to this:
var i = 0;
$.each(datas, function () {
str_one += "<dt class=\"glossquestion\">" + this['Question'] + "</dt>";
str_one += "<dd id=\"rand_" + i + "\" class=\"glossanswer\" style=\"-webkit-margin-start:0px\"><div class=\"answerbox\">" + this['Answer'] + "</div></dd>";
i++;
});
I'm just going to point out that my fix doesn't seem very jQuery-esque, and your entire code seems complicated for what it's doing.
If you changed your JSON to something like this:
[{"Question1":"..","Answer1":".."},{"Question2":"..","Answer2":".."}, .. ]
You could do this:
$.each(datas, function (i, v) {
str_one += "<dt class=\"glossquestion\">" + this['Question'] + "</dt>";
str_one += "<dd id=\"Dd" + i + "\" class=\"glossanswer\" style=\"-webkit-margin-start:0px\"><div class=\"answerbox\">" + this['Answer'] + "</div></dd>";
});
which is cleaner code than incrementing our own variable i inside $.each.

Categories

Resources