Turning dynamic div content into a link - javascript

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'] + '.';
};

Related

Show image from byte[] on CSHTML via javascript

I'm creating a timeline page with data from database, and I want to show a image from the object in the View.
The method Get it's working fine, when it returns the var imgSrc receives the data from the byte array converted to base64, but when I try to use the var in the it shows undefinied when I inspect the page.
Someone can give me a hand on how can I solve this?
$.getJSON("../ReportsAuditsTimeLine/GetAuditsResultbyAudit", { AuditID: ID },
function (data) {
var datafromaudit = '';
var div = document.createElement('div');
$('#timeLine').empty();
for (var i = 0; i < data.length; i++)
{
var base64 = "";
var imgSrc = "";
if (data[i].AUDIT_PICTURE != null)
{
//CHECK IMAGE
try {
base64 = Convert.ToBase64String(data[i].AUDIT_PICTURE);
imgSrc = String.Format("data:image/png;base64,{0}", base64);
console.log("Imagem:", imgSrc);
}
catch (Exception) {
}
//END IMAGE
}
if (data[i].AUDIT_ITEM_STATUS == "PASS") {
if (data[i].AUDIT_PICTURE != null) {
datafromaudit += '<li><i class="fa fa-camera bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + '<img src="' + $.imgSrc + '"class="margin" ></img>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
else
{
datafromaudit += '<li><i class="fa fa-pencil-square-o bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
}
}
CONTROLLER
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetAuditsResultbyAudit(string AuditID)
{
var viewModel = new ReportsAuditTimeLineViewModel();
int auditID = Int32.Parse(AuditID);
var auditResults = viewModel.GetAuditsResultbyAudit(auditID);
return Json(auditResults, JsonRequestBehavior.AllowGet);
}
VIEWMODEL
public List<AuditsResultData> GetAuditsResultbyAudit(int AuditID)
{
var list = new List<AuditsResultData>();
var context = new OnlineAuditsEntities();
using (context)
{
var query = from audits in context.tb_Audits
join i in context.tb_AuditItem on audits.AUDIT_ITEM_ID equals i.ID
join a in context.tb_Audit on audits.AUDIT_ID equals a.ID
join s in context.tb_Audit_ItemStatus on audits.STATUS_ID equals s.ID
where audits.AUDIT_ID == AuditID
select new { audits, i,a,s};
foreach (var s in query)
{
var Photo = (from pic in context.tb_AuditPictures
where pic.AUDIT_ID == s.audits.ID
select pic.PICTURE).FirstOrDefault();
if (Photo!=null)
{
list.Add(new AuditsResultData
{
ID = s.audits.ID,
AUDIT_ITEM_ID = s.audits.AUDIT_ITEM_ID,
DESCRIPTION = s.i.SUBCATEGORY_DESCRIPTION,
HASFIND = s.i.HAS_FINDING ?? false,
FINDS = s.audits.FINDINGS ?? 0,
STATUS_ID = s.audits.STATUS_ID,
AUDIT_ITEM_STATUS = s.s.STATUS_DESCRIPTION,
OD = s.audits.OD ?? 0,
COMMENTS = s.audits.COMMENTS,
SCANS = s.audits.SCANNED_CODE,
AUDIT_ID = s.audits.AUDIT_ID,
AUDIT_PICTURE = Photo
});
}
}
}
return list;
}
You should pass picture to view as Base64String from controller. Then convert it to picture like:
var picture = "data:image/jpg;base64," + data.base64image;

How to write a dynamic html tag

I have this for-in loop that is supposed to return a div element with an img tag that has an onclick function. For some reason I get this error - Uncaught SyntaxError: missing ) after argument list - I have no idea where I missed it. Any help or advice will be much appreciated. Thank you.
for (var key in icons) {
var legend = document.getElementById('legend');
//the variables below points to objects
var type = icons[key];
var name_place = type.name;
var icon = type.icon;
var div = document.createElement('div');
div.innerHTML = '<img' + ' src="' + icon + '"' +
'onclick="displayMarker( ' + name_place + ' )"' + '> ' + name_place;
legend.appendChild(div);
}
//When I try:
div.innerHTML = '<img' + ' src="' + icon + '"' +
'onclick="displayMarker(name_place)"> ' + name_place;
the variable name_place is not passed into the function
var icons = {
one: {
name: 'name1',
icon: 'icon1.img'
},
two: {
name: 'name2',
icon: 'icon2.img'
}
};
function displayMarker( arg) {
console.log("displayMarker argument %s value: %s", typeof arg, arg);
}
for (var key in icons) {
var legend = document.getElementById('legend');
//the variables below points to objects
var type = icons[key];
var name_place = type.name;
var icon = type.icon;
var div = document.createElement('div');
div.innerHTML = '<img src="' + icon + '" onclick="displayMarker(\'' + name_place + '\')"> ' + name_place;
legend.appendChild(div);
}
<div id="legend"></div>
You need to put add the quotation marks for the parameter for the function parameter.
Since you are already using the single quote for string representation, you need to escape \' the characters for parameter passing.
Suggestion: Use event delegation if possible.

Using jQuery to rearrange page elements

I'm relatively new to jQuery and JavaScript, and I think I understand what is causing my issue, but I'm not sure how to fix it.
I'm using SimpleWeather.JS , moment.js, and moment.js timezone to get the current time and weather for 4 cities. I have all the data I want on the page, but I want to move each city's time as the second paragraph in each city's div. Any ideas on how to get that working with my current code or is there a more efficient way of producing this result?
http://jsfiddle.net/ljd144/p6tpvz1r/
Here's my JS:
$(document).ready(function () {
$('.weather').each(function () {
var city = $(this).attr("city");
var woeid = $(this).attr("woeid");
var degrees = $(this).attr("degrees");
var continent = $(this).attr("continent");
$.simpleWeather({
zipcode: '',
woeid: woeid,
location: '',
unit: degrees,
success: function (weather) {
if (continent == 'America'){
html = '<p>' + weather.city + ', ' + weather.region + '</p>';
}
else {
html = '<p>' + weather.city + ', ' + weather.country + '</p>';
}
//html += '<p class="time" id="'+city+'></p>';
//html += '<p>' + weather.updated + '</p>';
html += '<p><i class="icon-' + weather.code + '"></i> ' + weather.temp + '°' + weather.units.temp + '<p>';
html += '<p>' + weather.currently + '<p>';
$('#weather_' + city).html(html);
},
error: function (error) {
$('#weather_' + city).html('<p>' + error + '</p>');
}
});
});
$(function () {
setInterval(function () {
$('.time').each(function () {
var city = $(this).attr("city");
var continent = $(this).attr("continent");
//$(this).text(city);
var utc = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(utc).toDate();
cityTime = moment(localTime).tz(continent + "/" + city).format('ddd MMM D YYYY, h:mm:ss a z');
$(this).text(city+ ': '+cityTime);
});
}, 1000);
});
$('.time').each(function () {
var city = $(this).attr("city");
//$('#weather_' + city).after(this);
});
});
You can use appendTo() method to append the time to the respective <div> having same city attribute using the attribute equals selector like:
$(this).text(city + ': ' + cityTime).appendTo("div[city='"+city+"']");
Updated fiddle
DEMO
Change:
$(this).text(city+ ': '+cityTime);
To:
var timeP = $('p.time','#weather_' + city);
timeP = timeP.length ? timeP : $('<p/>',{class:'time'}).appendTo( '#weather_' + city );
timeP.text(cityTime);

Why can't I update this table with the same code used in another place using Javascript?

The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>&nbsp&nbsp&nbsp&nbsp<button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>&nbsp&nbsp&nbsp&nbsp&nbsp<button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)

HTML read javascript and put result into a div

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();
I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

Categories

Resources