Using jQuery to rearrange page elements - javascript

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

Related

Load JS function inside a div

I have a simple span and I want to show full date from Javascript inside this span. I'm not getting how to do it.
HTML (The date would be in place of the "..."):
<h3>Data Atual: </h3><span id="date" onload="newDate()">...</span>
Javascript:
function newDate() {
var dateBox = document.getElementById('date');
dateBox.innerHTML = '';
var date = new Date();
var newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
dateBox.innerHTML += newDate;
}
Thanks in advance
The load event doesn't fire on static HTML elements, only elements that load their data asynchronously from an external URL.
Put the call in the body's onload event.
<body onload="newDate()">
you can use this code to show the complete day in your span text:
document.getElementById("date").innerHTML = createNewDate();
function createNewDate() {
const date = new Date();
const newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
return newDate;
}
do not need to load it on start. Actually you are using get dates wrongly. This following code will solve it your problem. Put it before </body>
<script>
var date = new Date();
var newDate = date.getDay() + ', ' + date.getDate() + ' de ' + date.getMonth() + ', ' + date.getFullYear() + '.';
document.getElementById("date").innerHTML = newDate;
</script>

Update status while Drag and drop in sharepoint list

I have Using Nestable js to drag and drop my list items .and the drag and drop is working fine in UI .but what i need is ,I want to update the status of list items after the item is dropped..How can i achieve this using javascript..
for reference of Nestable js https://codepen.io/Mestika/pen/vNpvVw
Next am retrieving the list items like bellow code
var ListEnumerator = this.myItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
var status = currentItem.get_item('Status');
if (status == "Planned") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridprocess').append(templateString);
}
else if (status == "In Process") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridinprogress').append(templateString);
}
else if (status == "Completed") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridcomplete').append(templateString);
}
else if (status == "Hold") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridincomplete').append(templateString);
}
}
here the li tag is used under
<div class="dd">
<ol class="dd-list" id="gridprocess" >
</ol>
</div>
how can i update the status while drag and drop? please give the code to do it..
Finally I achieved the above question . with the following code...... first i have set on ID to the class name dd as ddprocess like bellow
<div class="dd" id="ddprocess">
<ol class="dd-list" id="gridprocess">
</ol>
</div>
And Next I have Write a function When the id ddprocess is on change i get the Each item id and pass the ID to the Update function
$('#ddprocess').on('change', function () {
// JSON To get the list item in Process
var $this = $(this);
var serializedData = window.JSON.stringify($($this).nestable('serialize'));
// console.log("sData:", serializedData)
// convert the JSON into Object
var obj = JSON.parse(serializedData);
obj.forEach(myFunction);
function myFunction(item, index) {
var eachid = item.id;
// console.log("Item-id", eachid);//you will get id
Updatetoprocess(eachid);
}
});
Next the update function is to Update the status to planned for each item in the ddprocess id .....
function Updatetoprocess(eachid) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var siteurl = "https://abb.sharepoint.com/sites/IAPI-SOP";
var context = new SP.ClientContext(siteurl);
var olistnew = context.get_web().get_lists().getByTitle("TaskList");
var listitem = olistnew.getItemById(eachid);
listitem.set_item('Status', 'Planned');
listitem.update();
context.load(listitem);
context.executeQueryAsync(function () {
alert("Items Updated successfully");
},
function () { console.log("failure") }
)
});
}
Thank you

script external link into a js file

Can someone help me to "convert" a external js script from a html page into a script in a .js file??
I have a countdown script, and a part of it is with these external link and i don't like it, can i put him into a js fie ??
<script type="text/javascript">
$(function() {
var endDate = "June 7, 2087 15:03:25";
$('.countdown.simple').countdown({ date: endDate });
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.years, 4) + " <span>years</span></div><div>" + this.leadingZeros(data.days, 3) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hrs</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>min</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>sec</span></div>");
}
});
$('.countdown.callback').countdown({
date: +(new Date) + 10000,
render: function(data) {
$(this.el).text(this.leadingZeros(data.sec, 2) + " sec");
},
onEnd: function() {
$(this.el).addClass('ended');
}
}).on("click", function() {
$(this).removeClass('ended').data('countdown').update(+(new Date) + 10000).start();
});
// End time for diff purposes
var endTimeDiff = new Date().getTime() + 15000;
// This is server's time
var timeThere = new Date();
// This is client's time (delayed)
var timeHere = new Date(timeThere.getTime() - 5434);
// Get the difference between client time and server time
var diff_ms = timeHere.getTime() - timeThere.getTime();
// Get the rounded difference in seconds
var diff_s = diff_ms / 1000 | 0;
var notice = [];
notice.push('Server time: ' + timeThere.toDateString() + ' ' + timeThere.toTimeString());
notice.push('Your time: ' + timeHere.toDateString() + ' ' + timeHere.toTimeString());
notice.push('Time difference: ' + diff_s + ' seconds (' + diff_ms + ' milliseconds to be precise). Your time is a bit behind.');
$('.offset-notice').html(notice.join('<br />'));
$('.offset-server .countdown').countdown({
date: endTimeDiff,
offset: diff_s * 1000,
onEnd: function() {
$(this.el).addClass('ended');
}
});
$('.offset-client .countdown').countdown({
date: endTimeDiff,
onEnd: function() {
$(this.el).addClass('ended');
}
});
});
</script>
There is the code.
Thanks in advance :D
Yes, you can. Create a new file and call it countdown.js and place it in the same folder as your html file.
Then from inside your html page add
<script src="countdown.js"></script>

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)

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