I'm trying to add background image using Javascript CSS property. My code does not work. If I add 'url' directly, it worked. Is 'weatherImage' variable a problem..?
Javascript
var OpenWeatherKey = 'API key';
var locationUrl = 'http://freegeoip.net/json/';
function getLocation(){
$.ajax({
url : locationUrl,
dataType: "json",
success : function(data){
var country = data['country_name'];
var city = data['city'];
var latitude = data['latitude'];
var longitude = data['longitude'];
$('#location').html(city + ', ' + country);
var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
getWeather(Weather);
}
});
}
function getWeather(url){
$.ajax({
url:url,
dataType:"json",
success: function(data){
var weather = data['weather'][0]['main'];
var temp = data['main']['temp'];
var icon = data['weather'][0]['icon'];
var id = data['weather'][0]['id'];
document.getElementById('icon').src="http://openweathermap.org/img/w/" + icon + ".png";
$('#weather').html(weather);
$('#temp').html(temp);
// Change F to C, C to F
var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
var celsius = Math.floor((temp)- 273.15) + '\xB0C';
var $tempDisplay = $("#temp");
$tempDisplay.html(celsius);
$("#button-f").on('click', function() {
$tempDisplay.html(fahrenheit);
});
$("#button-c").on('click', function() {
$tempDisplay.html(celsius);
});
// change Background image
var imagePhoto = {
thunder: "http://www.tabinotebook.com/wp-
content/uploads/2017/02/jeremy-bishop-72584.jpg",
rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg",
}
var weatherImage = "";
function selectImage (id){
if(id >= 200 && id <= 232){
weatherImage = imagePhoto.thunder;}
else if (id >= 300 && id <= 531){
weatherImage = imagePhoto.rainy;}
else if (id >= 600 && id <= 622){
weatherImage = imagePhoto.snow;}
else if (id >= 801 && id <= 804){
weatherImage = imagePhoto.cloudy;}
else if (id === 800){
weatherImage = imagePhoto.sunny;}
else {
weatherImage = imagePhoto.cloudy;}
}
// we set the background first after the weatherImage has been assigned a value
// above
$('body').css('background-image','url(' + weatherImage + ')');
selectImage(800);
}
});
};
getLocation();
Thank you so much in advance.
You need to add the actual contents of the variable weatherImage, right now you're just setting the url to the name of the variable. Try changing your code to:
$('body').css('background-image', 'url(' + weatherImage + ')');
It is a little hard to tell what is not working since you don't have included the entire script and you also don't show how and where you call selectImage(). The following should work though:
// change api key to whatever you are using
var OpenWeatherKey = 'your-api-key';
var locationUrl = 'http://freegeoip.net/json/';
var weatherImage = "";
var imagePhoto = {
thunder: "http://www.tabinotebook.com/wp-content/uploads/2017/02/jeremy-bishop-72584.jpg",
rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg"
};
function selectImage (id) {
if(id >= 200 && id <= 232) {
weatherImage = imagePhoto.thunder;
}
else if (id >= 300 && id <= 531) {
weatherImage = imagePhoto.rainy;
}
else if (id >= 600 && id <= 622) {
weatherImage = imagePhoto.snow;
}
else if (id >= 801 && id <= 804) {
weatherImage = imagePhoto.cloudy;
}
else if (id === 800) {
weatherImage = imagePhoto.sunny;
}
else {
weatherImage = imagePhoto.cloudy;
}
// we set the background first after the weatherImage has been assigned a value
// above
$('body').css('background-image','url(' + weatherImage + ')');
}
function getLocation(){
$.ajax({
url : locationUrl,
dataType: "json",
success : function(data){
var country = data['country_name'];
var city = data['city'];
var latitude = data['latitude'];
var longitude = data['longitude'];
$('#location').html(city + ', ' + country);
var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
getWeather(Weather);
}
});
}
function getWeather(url){
$.ajax({
url:url,
dataType:"json",
success: function(data) {
var weather = data['weather'][0]['main'];
var temp = data['main']['temp'];
var icon = data['weather'][0]['icon'];
var id = data['weather'][0]['id'];
document.getElementById('icon').src= "http://openweathermap.org/img/w/" + icon + ".png";
$('#weather').html(weather);
$('#temp').html(temp);
// Change F to C, C to F
var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
var celsius = Math.floor((temp)- 273.15) + '\xB0C';
var $tempDisplay = $("#temp");
$tempDisplay.html(celsius);
$("#button-f").on('click', function() {
$tempDisplay.html(fahrenheit);
});
$("#button-c").on('click', function() {
$tempDisplay.html(celsius);
});
// select background image based on id
selectImage(id);
}
});
};
getLocation();
Related
I want to create an application that allows a user to join multiple video call rooms in kurento.
I wrote the following code:
function joinRooms() {
var userId = document.getElementById('expertid').value;
console.log("UserID = " + userId);
var roomIds = document.getElementById('roomids').value.split(",");//Assume that we have 2 rooms r1 & r2
var userIdAlias = [];
for (var i = 0; i < roomIds.length; i++) {
userIdAlias[i] = userId + "(" + i + ")";
console.log("User alias = " + userIdAlias[i]);
}
var wsUri = 'wss://' + location.host + '/room';
kurento = KurentoRoom(wsUri, function(error, kurento) {
if (error)
return console.log(error);
for (let i = 0; i < roomIds.length; i++) {
//console.log("Start loop Roomid = " + roomId);
rooms[i] = kurento.Room({
room : roomIds[i],
user : userIdAlias[i],
subscribeToStreams : true
});
localStreams[i] = kurento.Stream(rooms[i], {
audio : true,
video : true,
data : true
});
localStreams[i].addEventListener("access-accepted", function() {
var playVideo = function(stream) {
var participantId = stream.getParticipant().getID();
var userId = document.getElementById('expertid').value;
console.log("userId = " + userId + ", participantId = " + participantId);
if (!userIdAlias.includes(participantId)) {
var elementId = "video-" + stream.getGlobalID();
var div = document.createElement('div');
div.setAttribute("id", elementId);
document.getElementById("participants").appendChild(div);
stream.playThumbnail(elementId);
// Check color
var videoTag = document.getElementById("native-" + elementId);
var userId = stream.getGlobalID();
var canvas = document.createElement('CANVAS');
checkColor(videoTag, canvas, userId);
}
}
rooms[i].addEventListener("room-connected", function(){
var j = i;
return function(roomEvent) {
document.getElementById('room-header').innerText = 'ROOM \"'
+ roomIds[j] + '\"';
//document.getElementById('join').style.display = 'none';
document.getElementById('room').style.display = 'block';
localStreams[j].publish();
var streams = roomEvent.streams;
for (var streamsIdx = 0; streamsIdx < streams.length; streamsIdx++) {
playVideo(streams[streamsIdx]);
}
}
});
rooms[i].addEventListener("stream-added", function(streamEvent) {
playVideo(streamEvent.stream);
});
rooms[i].addEventListener("stream-removed", function(streamEvent) {
var element = document.getElementById("video-"
+ streamEvent.stream.getGlobalID());
if (element !== undefined) {
element.parentNode.removeChild(element);
}
});
playVideo(localStreams[i]);
rooms[i].connect();
});
localStreams[i].init();
}
});
}
However, the code does not work. The log in server said that there is only one user request to join room r2 but not r1.
I think the reason is Javascript works with too many asynchronous task so it worked incorrectly.
Can you give some advice about the way to joining multiple rooms in kurento?
I'm trying to create an image file dynamically, based on the contents retrieved from S3 Bucket. Got CORS working fine, here's the code I've written:
/**
* #name fetchFile
* #desc Fetch the desired file, and add to our _filesPending array, and update dialog process
* #author cgervais
*/
var _filesPending = [];
var _fileMessageDialog = "Currently downloading {{numberOfFiles}} videos...";
var _filesDownloadedSoFar = 0;
var _filesDownloaded = [];
var downloading = false;
function OKDownload(response, fileName) {
var responsePerfect = {
link: function() {
var _tmpResponse = JSON.parse(response);
return _tmpResponse.location;
}
};
$.ajax({
type: "GET",
url: responsePerfect.link(),
data: {},
success: function(answer) {
var _tmpFileObject = {
fUrl: fileName,
fContent: btoa(unescape(encodeURIComponent(answer.trim())))
};
_filesDownloaded.push(_tmpFileObject);
_filesDownloadedSoFar = _filesDownloadedSoFar + 1;
console.log('Downloaded -- so far: ' + _filesDownloadedSoFar);
},
error: function(response, errorCode, errorMessage) {
console.log('[OKDownload] ' + response + ' - ' + errorCode + ' - ' + errorMessage + ' // ' + responsePerfect.link);
}
})
}
var _alreadyGeneratedRStrings = [];
function generateReasonableString(min, max, fnMax) {
var _genStringSeed = Date.now() + 10;
var _randomString = '';
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=min; i < max; i++ )
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
_randomString = btoa(text + '::' + _genStringSeed);
if(_randomString.indexOf('==') > -1) {
_randomString = _randomString.replace('==','');
}
if(_randomString.length > fnMax) {
_randomString = _randomString.substring(0, fnMax);
}
if(_alreadyGeneratedRStrings.indexOf(_randomString) > -1) { _randomString = generateReasonableString(min, max, fnMax); }
_alreadyGeneratedRStrings.push(_randomString);
return _randomString;
}
function httpRawFetch(link) {
var matched = generateReasonableString(8, 26, 8) + ".jpg";
$.ajax({
type: "GET",
url: link.href + "&rawlink=yes",
data: {},
success: function(answer) {
if(answer === "") { console.log('[httpRawFetch] Failed fetching ' + link); return; }
OKDownload(answer, matched);
},
error: function(response, errorCode, errorMessage) {
console.log('[httpRawFetch] Error fetching JSON data from backend server.');
console.log('[DEBUG] ' + response + ' - ' + errorCode + ' - ' + errorMessage);
console.log('[DEBUG] Link: ' + link);
}
})
}
function generateDownloadModal() {
var _tmpHTML;
// #TODO: generate side modal with jQuery
}
function downloadFinished() {
var zip = new JSZip();
var _runningCountOfFiles = 0;
var _runningAddFiles = true;
for(var i = 0; i < _filesDownloaded.length; i++) {
_runningAddFiles = true;
// zip create file ( fileName, fileContent )
zip.file(_filesDownloaded[i].fUrl, decodeURIComponent(escape(atob(_filesDownloaded[i].fContent))));
_runningCountOfFiles++;
}
var recInterval = setInterval(function() {
if(_runningAddFiles && _runningCountOfFiles == _filesDownloaded.length || _runningCountOfFiles > _filesDownloaded.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "recordings.zip");
_runningAddFiles = false;
clearInterval(recInterval);
});
}
}, 1000);
}
setInterval(function() {
if(downloading) {
if(_filesDownloadedSoFar === _filesDownloaded.length) {
downloadFinished();
downloading = false;
}
}
}, 60000);
function fetchFile(link) {
if(link === "") {
alert('Cannot download this file.');
return;
}
_filesPending.push(link);
httpRawFetch(link);
downloading = true;
}
The issue:
It creates the zip with files, then it downloads to my machine. I open the image file, I get an error (all of them): "We can't open this file"
What am I doing wrong? They're JPG images.
My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);
I have phone numbers on my website that are automatically inserted via a JavaScript to display either a default phone number (that's defined within the primary JavaScript) or change to a variable phone number if the webpage is accessed by a URL string with the phone number in it - for example:
http:www.website.com?tfid=8005551212
What I need to do is make the phone numbers clickable for mobile users so that whichever phone number appears they can click it and it will call the phone number.
I understand that if you wrap the phone number with an anchor with the tel: attribute it will launch the click-to-call function, but how can the tag be written so it will allow for the phone number variable to be passed? ex:
variable telephone number
Do you mean this?
Please rewrite your script to not use document.write. If you ever call one of your functions after the page loaded it will wipe the page.
document.getElementById("phonenumber").innerHTML=''+phone_number+'';
Like this, using your original code
<div id="phonenumber">Call: </div>
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
window.onload=function() {
document.getElementById("phonenumber").innerHTML+=getPhone();
}
Full code
function pixelfire(debug) {
var phone_number = getVar("phone_number");
var keyword = getVar("keyword");
var source = getVar("source");
if (keyword) {
setcookie(keyword, phone_number);
} else {
var keyword = get_named_cookie("MM_Keyword");
var phone_number = get_named_cookie("MM_TrackableNumber");
return keyword || null;
}
var campaign = getVar("campaign");
var content = getVar("content");
var url = "http://www.mongoosemetrics.com/pixelfire.php?phone_number=" + phone_number;
var url = url + "&keyword=" + keyword;
var url = url + "&source=" + source;
var url = url + "&campaign=" + campaign;
var url = url + "&content=" + content;
myImage = new Image();
myImage.src = url;
}
function setcookie(key, tn, path) {
index = -1;
var today = new Date();
today.setTime(today.getTime());
var cookie_expire_date = new Date(today.getTime() + (365 * 86400000));
document.cookie = "MM_TrackableNumber=" + tn + ";path=/;expires=" + cookie_expire_date.toGMTString();
document.cookie = "MM_Keyword=" + key + ";path=/;expires=" + cookie_expire_date.toGMTString();
}
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
function get_named_cookie(name) {
if (document.cookie) {
index = document.cookie.indexOf(name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
var ret_one = document.cookie.substring(namestart, nameend);
return ret_one;
}
}
}
//function to format the phonenumber to (123) 456-7890
function formatnumber(num) {
_return = "1-";
var ini = num.substring(0, 3);
_return += ini + "-";
var st = num.substring(3, 6);
_return += st + "-";
var end = num.substring(6, 10);
_return += end;
return _return;
}
function getVar(name) {
get_string = document.location.search;
return_value = '';
do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');
if (name_index != -1) {
get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
end_of_value = get_string.indexOf('&');
if (end_of_value != -1) value = get_string.substr(0, end_of_value);
else value = get_string;
if (return_value == '' || value == '') return_value += value;
else return_value += ', ' + value;
}
} while (name_index != -1)
//Restores all the blank spaces.
space = return_value.indexOf('+');
while (space != -1) {
return_value = return_value.substr(0, space) + ' ' + return_value.substr(space + 1, return_value.length);
space = return_value.indexOf('+');
}
return (return_value);
}
window.onload = function () {
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if (tn != "") {
setcookie(key, tn);
}
var phone_number = getPhone();
document.getElementById("phonenumber").innerHTML+=''+phone_number+'';
}
I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}