Why does getting a LocalStorage item yield “undefined”? - javascript

We are using PhoneGap to develop a pedometer app using the iPhone accelerometer.
Below is a copy of the code we are currently running:
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer</title>
<script type="text/javascript" charset="utf-8" src="js/cordova-1.7.0rc1.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
var stepCount = 0;
window.localStorage.setItem('exp');
var expGain = 0;
var totalExp = window.localStorage.getItem('exp');
var userAge = window.localStorage.getItem('age');
var handicap = 0;
if (userAge <= 10) {
handicap = 10;
} else if (userAge > 10) {
handicap = 5;
}
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//e7
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 5 seconds
var options = {
frequency: 1000
};
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//count steps and calculate experience gained
function countSteps(accelx, timestamp, expGain, totalExp) {
var element = document.getElementById('accelerometer');
//var accCount = Math.round(acceleration.x);
//stepCount = stepCount + Math.abs(accCount);
stepCount = stepCount + 1;
expGain = stepCount * handicap;
totalExp = totalExp + expGain;
//window.localStorage.setItem('exp', totalExp);
element.innerHTML = '<br>Step Count: ' + stepCount + '<br/>' +
'Acceleration X: ' + Math.abs(accelx) + '<br />' +
'Timestamp: ' + timestamp + '<br />' +
'Experience: ' + totalExp + '<br />';
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
var accelx = Math.round(acceleration.x)
var timestamp = acceleration.timestamp
//element.innerHTML = 'Acceleration X: ' + Math.abs(accelx) + '<br />' +
//'Acceleration Y: ' + acceleration.y + '<br />' +
//'Acceleration Z: ' + acceleration.z + '<br />' +
//'Timestamp: ' + acceleration.timestamp + '<br />';
if (Math.abs(accelx) > 1) {
countSteps(accelx, timestamp, expGain, totalExp);
}
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<link media="only screen and (max-device-width: 480px)" href="css/iPhone.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
<br />
<p>back
</p>
</body>
</html>
The issue is: we keep getting an "undefined" next to our result for window.localStorage.setItem('exp');. We have been working all day to try and work this one out.

setItem takes two arguments (a key and a value). If you don't specify an argument, then undefined is the default value.
window.localStorage.setItem('exp'); means window.localStorage.setItem('exp', undefined);
If you want it to have some other value, then you need to specify it.

Doesn't localStorage.setItem require a second parameter? Have you tried:
window.localStorage.setItem("exp","");

Related

Tizen web app works on simulator, but doesn't work on gear 3

I'm trying to develop an app that reads data from the acceleration sensor, and save it on a text file. Using web app development, I've managed to make the app work on the emulator, but when I tried it on Samsung Gear 3 frontier, it didn't work. Can some figure out what I did wrong?
Below are the html and the java script code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
Java script code:
function init() {
console.log("app started");
document.getElementById("readings").innerHTML="Starting";
accelerationSensor=tizen.sensorservice.getDefaultSensor("ACCELERATION");
if (accelerationSensor){
console.log("Sensor captured");
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData)
{
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
x = sensorData.x;
y = sensorData.y;
z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir)
{
var newFile = dir.resolve("newFilePath.txt");;
newFile.openStream(
"a",
function(fs) {
fs.write(Date+"\t x:"+x+"\t y:"+y+"\t z:"+z+"\n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
document.getElementById("readings").innerHTML="Reading";
}
function onerrorCB(error)
{
console.log("error occurred: " + error.message);
}
function onsuccessCB()
{
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours(),
var minute = datetime.getMinutes(),
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir)
{
newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour+":"+minute+":"+second+"\tstart of recording \n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
}
function updateTime() {
accelerationSensor.getAccelerationSensorData(onGetSuccessCB, onerrorCB);
}
(function () {
window.addEventListener("tizenhwkey", function (ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {
}
} else {
window.history.back();
}
}
});
}());
Thanks in advance.
I've managed to find the solution, and I post it for helping others who would face the same issue.
It turns out that there is no acceleration sensor in S3, and everything works fine when I change the sensor from Acceleration to linear_acceleration. The codes for both html and javascript are as follow:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
The javascript:
var accelerationSensor;
function onsuccessCB() {
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour + ":" + minute + ":" + second + "\tstart of recording \n");
fs.close();
document.getElementById("readings").innerHTML = "Reading";
},
function(e) {
document.getElementById("readings").innerHTML = "File Error";
}, "UTF-8");
});
}
function init() {
console.log("app started");
document.getElementById("readings").innerHTML = "Starting";
accelerationSensor = tizen.sensorservice.getDefaultSensor("LINEAR_ACCELERATION");
document.getElementById("readings").innerHTML = "Starting1";
if (accelerationSensor) {
console.log("Sensor captured");
document.getElementById("readings").innerHTML = "Acceleration";
} else {
document.getElementById("readings").innerHTML = "Error";
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
document.getElementById("readings").innerHTML = "onsuccessCB done";
console.log("onsuccessCB done");
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData) {
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
var x = sensorData.x;
var y = sensorData.y;
var z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.resolve("newFilePath.txt");
newFile.openStream(
"a",
function(fs) {
fs.write(Date + "\t x:" + x + "\t y:" + y + "\t z:" + z + "\n");
fs.close();
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
}, function() {
document.getElementById("readings").innerHTML = "Error";
});
document.getElementById("readings").innerHTML = "Reading";
}
function onerrorCB(error) {
console.log("error occurred: " + error.message);
}
function updateTime() {
accelerationSensor.getLinearAccelerationSensorData(onGetSuccessCB);
}
(function() {
window.addEventListener("tizenhwkey", function(ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {}
} else {
window.history.back();
}
}
});
}());
The above code will get linear_acceleration sensor readings, and save them to a text file in "Documents" folder.
You need filesystem.read and filesystem.write privileges to have access to "Document" folder.

Cordova: HTML5 geolocation - find the nearest place from JavaScript array

I have array of places in JavaScript. I need to get gps geolocation from gps sensor (on mobile phone using Apache Cordova).
If GPS accuracy is better than for example 40 meters, I need to do something (set css display:block, change color, ...).
I have this code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/distance.js"></script> <!-- https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js -->
<script type="text/javascript" charset="utf-8">
var interval = 5; // [s]
var timeout = 60; // [s]
/* --------------------------------------------------- */
var latitude = new Array();
var longtitude = new Array();
var nameOfLocation = new Array();
// address 1
// Latitude : 10.20 | Longitude : 30.40
latitude[0] = 10.20;
longtitude[0] = 30.40;
nameOfLocation[0] = "address 1";
// address 2
// Latitude : 40.30 | Longitude : 20.10
latitude[1] = 40.30;
longtitude[1] = 20.10;
nameOfLocation[1] = "address 2";
// ...
/* --------------------------------------------------- */
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
console.log('in onDeviceReady()');
$(document).ready(function(){
setInterval(function(i) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 0,
timeout: (timeout*1000),
enableHighAccuracy: true }
);
}, (interval*1000))
});
}
// onSuccess Geolocation
function onSuccess(position) {
console.log('in onSuccess()');
console.log(position.coords.latitude, "position.coords.latitude");
console.log(position.coords.longitude, "position.coords.longitude");
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
var place;
var accuracy;
$("#accuracy").html("GPS accuracy " + position.coords.accuracy + " m.");
if (position.coords.accuracy < 40) {
$("#accuracy").css("background-color", "Gray");
for (var i=0; nameOfLocation.length; i++) {
var distance = getDistance(latitude[0], longitude[0], position.coords.latitude, position.coords.longitude);
if (distance <= 25) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "OrangeRed");
} else if (distance <= 20) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Yellow");
} else if (distance <= 15) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Green");
}
}
$("#info").html("You are about <strong>" + accuracy + "</strong> meters from location <strong>" + nameOfLocation[i] + "</strong>");
} else {
$("#info").html("");
}
}
// onError Callback receives a PositionError object
function onError(error) {
console.log('in onError()');
console.log(error.code, "error.code");
console.log(error.message, "error.message");
$("#geolocation").html(
'code: ' + error.code + '<br />' +
'message: ' + error.message);
$("#accuracy").css("background-color", "");
}
</script>
</head><body>
<p id="info"></p>
<hr />
<p id="accuracy"></p>
<hr />
<p id="geolocation">GPS ...</p>
</body></html>
I use this JS lib for distance measurement of two GPS locations https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js
I can't use google online gps distance lib. App must work without internet connection.
If I run app it start location gps. After first finding location any next finding take only about 5 seconds and after that stop finding locations (this repeats to infinity). I need permanent searching.
Do you know where is an error?
I'm going to do it well?

JavaScript passing coordinates from one function to another

I am having issues passing two coordinates from one function to another. I don't really know JavaScript, but it seems to be somewhat correct. Could you please let me know where is my error?
<head>
<script>
var zoom = 12; // 18 for mobile phones because the geolocation is more accurate
function init() {
// Don't bother if the web browser doesn't support cross-document messaging
if (window.postMessage) {
if (navigator && navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(pPos) {
send(pPos.coords.latitude, pPos.coords.longitude);
}, function() {});
} catch (e) {}
} else if (google && google.gears) {
// Relevant if targeting mobile phones (some of which may have Google Gears)
try {
var geoloc = google.gears.factory.create("beta.geolocation");
geoloc.getCurrentPosition(function(pPos) {
send(pPos.latitude, pPos.longitude);
}, function() {});
} catch (e) {}
}
}
}
function send(pLat, pLng) {
var myiframe = document.getElementById("myiframe").contentWindow;
// The third parameter, zoom, is optional
myiframe.postMessage(pLat + "," + pLng + "," + zoom, "http://www.qib.la");
}
window.onload=init;
</script>
</head>
<body>
<iframe id="myiframe" src="http://www.qib.la/embed/" width="400" height="400">
Check the prayer direction towards the Ka'ba in Makkah at
Qibla Direction.
</iframe>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<br>
<p align="center">Waterloo, ON, Canada<p>
<div align="center" id="table"></div>
<script type="text/javascript">
var date = new Date(); // today
var times = prayTimes.getTimes(date, pLat + "," + pLng, -5);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
</script>
</body>
Is it possible to return a value from an asynchronous function? How do I use a callback here?
You have a syntax error in this code:
var times = prayTimes.getTimes(date, + b + ',' + c + , -5);
You have a "+" and then a comma immediately following it. I'm not sure what your intent for the code was, but that is what is causing it to not run.
Perhaps you intended to follow the pattern of appending the commas as strings?
var times = prayTimes.getTimes(date + ',' + b + ',' + c + ',' + -5);
Or perhaps that -5 was meant to be a separate argument?
var times = prayTimes.getTimes(date, b + ',' + c, -5);

User control(.ascx) and java script functions

In default.aspx page, there is a user control side_menu.ascx.
This is part of the code in side_menu.ascx
<script src="../library/scripts/side_menu.js" type="text/javascript"></script>
<script src="../library/scripts/side_menu_items.js" type="text/jscript"></script>
<script src="../library/scripts/side_menu_tpl.js" type="text/jscript"></script>
<script language="JavaScript" type="text/javascript">
<!--
new menu(SIDE_MENU_ITEMS, SIDE_MENU_POS, SIDE_MENU_STYLES);
// -->
</script>
The function menu is defined in side_menu.js. SIDE_MENU_ITEMS is an array containing all the menu items and the path.
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", "administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", "administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", "administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", "administration/features/feature_tracker.aspx"] // /TOrders/
]
When a menu item is clicked it, it loads the page /localhost/administration/bugs/whateverpage.aspx. This works fine. However, when a menu item is clicked the second time the path becomes /localhost/administration/bugs/administration/bugs/whateverpage.aspx. THE PATH is getting appended. I just cant figure out where to go and clear the array. When I click on the the menu item, the menu_onnclick() is called and this.item[id] is already populated with the wrong path. Not sure where to clear it.
Here are some of the function in side_menu.js
function menu (item_struct, pos, styles) {
this.item_struct = item_struct;
this.pos = pos;
this.styles = styles;
this.id = menus.length;
this.items = [];
this.children = [];
this.add_item = menu_add_item;
this.hide = menu_hide;
this.onclick = menu_onclick;
this.onmouseout = menu_onmouseout;
this.onmouseover = menu_onmouseover;
this.onmousedown = menu_onmousedown;
var i;
for (i = 0; i < this.item_struct.length; i++)
new menu_item(i, this, this);
for (i = 0; i < this.children.length; i++)
this.children[i].visibility(true);
menus[this.id] = this;
}
function menu_add_item (item) {
var id = this.items.length;
this.items[id] = item;
return (id);
}
function menu_onclick (id) {
var item = this.items[id];
return (item.fields[1] ? true : false);
}
function menu_item (path, parent, container) {
this.path = new String (path);
this.parent = parent;
this.container = container;
this.arrpath = this.path.split('_');
this.depth = this.arrpath.length - 1;
// get pointer to item's data in the structure
var struct_path = '', i;
for (i = 0; i <= this.depth; i++)
struct_path += '[' + (Number(this.arrpath[i]) + (i ? 2 : 0)) + ']';
eval('this.fields = this.container.item_struct' + struct_path);
if (!this.fields) return;
// assign methods
this.get_x = mitem_get_x;
this.get_y = mitem_get_y;
// these methods may be different for different browsers (i.e. non DOM compatible)
this.init = mitem_init;
this.visibility = mitem_visibility;
this.switch_style = mitem_switch_style;
// register in the collections
this.id = this.container.add_item(this);
parent.children[parent.children.length] = this;
// init recursively
this.init();
this.children = [];
var child_count = this.fields.length - 2;
for (i = 0; i < child_count; i++)
new menu_item (this.path + '_' + i, this, this.container);
this.switch_style('onmouseout');
}
function mitem_init() {
document.write (
'<a id="mi_' + this.container.id + '_'
+ this.id +'" class="m' + this.container.id + 'l' + this.depth
+'o" href="' + this.fields[1] + '" style="position: absolute; top: '
+ this.get_y() + 'px; left: ' + this.get_x() + 'px; width: '
+ this.container.pos['width'][this.depth] + 'px; height: '
+ this.container.pos['height'][this.depth] + 'px; visibility: hidden;'
+' background: black; color: white; z-index: ' + (this.depth + 10000) + ';" ' // changed this.depth to (this.depth + 10000)
+ 'onclick="return menus[' + this.container.id + '].onclick('
+ this.id + ');" onmouseout="menus[' + this.container.id + '].onmouseout('
+ this.id + ');window.status=\'\';return true;" onmouseover="menus['
+ this.container.id + '].onmouseover(' + this.id + ');window.status=\''
+ this.fields[0] + '\';return true;"onmousedown="menus[' + this.container.id
+ '].onmousedown(' + this.id + ');"><div class="m' + this.container.id + 'l'
+ this.depth + 'i">' + this.fields[0] + "</div></a>\n"
);
this.element = document.getElementById('mi_' + this.container.id + '_' + this.id);
}
Change your array to:
var url="http://"+window.location.hostname;
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", url+"/administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", url+"/administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", url+"/administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", url+"/administration/features/feature_tracker.aspx"] // /TOrders/
]
];
Or (The more general way for support the urls with port numbers such as http://localhost:51143/):
function getUrl(){
url = window.location.href.split('/');
return url[0]+'//'+url[2];
}
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", getUrl()+"/administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", getUrl()+"/administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", getUrl()+"/administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", getUrl()+"/administration/features/feature_tracker.aspx"] // /TOrders/
]
];

Turning dynamic div content into a link

I am working on Longtail's JW Player and I am stuck with some basic stuff. I don't know what it is called in the programming language thats why I will write it step by step:
There is a javascript code to show title and description of the playing video, as shown below
<script type="text/javascript">
var player = null;
var playlist = null;
function playerReady(obj)
{
player = gid(obj.id);
displayFirstItem();
};
function displayFirstItem()
{
try
{
playlist = player.getPlaylist();
}
catch(e)
{
setTimeout("displayFirstItem()", 100);
}
player.addControllerListener('ITEM', 'itemMonitor');
itemMonitor({index:player.getConfig()['item']});
};
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
};
function gid(name)
{
return document.getElementById(name);
};
</script>
Code returns the video title in to a div:
<div id="nowplaying"></div>
What I want is to display video title also in the tweet this button:
href="http://twitter.com/home?status=SONG TITLE"
How can I do this? Best regards
Edit the itemMonitor() function:
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
gid('tweetLink').href = 'http://twitter.com/home?status=' + encodeURIComponent(playlist[obj.index]['title']);
};
This requires that a link be present in the document with id="tweetLink", this doesn't alter the link's text, however, if you want to update the link's text:
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
gid('tweetLink').href = 'http://twitter.com/home?status=' + encodeURIComponent(playlist[obj.index]['title']);
gid('tweetLink').innerHTML = 'Tweet this song: ' + playlist[obj.index]['title'] + '.';
};

Categories

Resources