Javascript Chat text to the bottom - javascript

I've created a chat system with javascript. The sent messages are on the right, the received on the left.
Now I want to display them on the bottom (currently they are on the top). But if I set the parent div to the bottom, then both sent and received messages are displayed on one side.
css: Screenshot because this page cannot format my css wow..
https://s15.postimg.org/kav7m3x3v/css_SO.png
win.document.getElementById('input-text-chat').onkeyup = function (e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
var d = a.getSeconds();
if (b < 10) {
b = '0' + b;
}
if (c < 10) {
c = '0' + c;
}
if (d < 10) {
d = '0' + d;
}
var time = b + ':' + c + ':' + d;
if (!this.value.length) return
connection.send('<div class="chat-OutputGET bubbleGET"> <font color="white"> User(' + time + '): ' + this.value + '</font></div>');
console.log(connection.send);
console.log('User (' + time + '): ' + this.value);
appendDIV('<div class="chat-OutputSEND bubble"> <font color="white"> Me (' + time + '): ' + this.value + '</font></div>');
this.value = '';
};
var chatContainer = win.document.querySelector('.chat-output');
function appendDIV(event) {
console.log(event);
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.appendChild(div);
div.tabIndex = 0;
div.focus();
win.document.getElementById('input-text-chat').focus();
}
connection.onmessage = appendDIV;
}
<div id="chatHtml" style="display: none;">
<link rel="stylesheet" href="style/main.css">
<div id=chatOutput class="chat-output"></div>
<textarea class="form-control" rows="1" id="input-text-chat" placeholder="Enter Text Chat"></textarea>
<div id="chat-container">
</div>
</div>

Its done, i change the position of "chat-output" to absolut and the important point is to set left and right to 0.

Related

jQuery function conversion

I've been working on this script that I am using with a WordPress plugin I wrote for our blogs at work. I'm stripping it down to make it a pure jQuery plugin but most of the questions I've seen where for getting the plugin to work like this:
$('.some-target').cta();
Whereas I want to write it so that the user can do something like:
cta();
or
$.cta
I'm not really getting clear answers or seeing many guides covering this, or really if it's possible. In the end I want it to work like it's original iteration for WP, but as a stand alone jQuery plugin for static sites:
cta({
text: "Some Text",
icon: "Some-icon.jpg",
dist: 50
});
Here is the original code:
jQuery(document).ready(function($){
cta = function(o) {
o = o || {};
var bgColor = o.bgColor;
var url = o.url;
var text = o.text;
var icon = o.icon;
var buttonText = o.buttonText;
var target = o.target;
var dist = o.dist;
if((o.icon != null) || o.icon == "" ) {
jQuery('body').append(
'<div class="cta-popup-wrapper with-icon"><div class="cta-popup"><span class="close-trigger">X</span><img class="cta-icon" src="' + icon + '" alt="Call to Action Icon"><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
} else {
jQuery('body').append(
'<div class="cta-popup-wrapper without-icon"><div class="cta-popup"><span class="close-trigger">X</span><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
}
if(target != null) {
var t = $(target);
if(t.length) {
$(window).scroll(function() {
var hT = t.offset().top,
hH = t.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
} else {
if((dist != null) && (dist > 0)) {
var b = $('body').innerHeight();
dist = dist / 100;
var trigger = b * dist;
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS > trigger){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
}
}
});

Google Script/JavaScript Converting time between timezones

I travel a lot, and I often have appointments (such as flights) that start in one timezone and end in another. I need to know both the local and UTC time that each event will start and end.
I use Google Calendar and specify the different start and end timezones in the calendar events.
I have written a script that pulls my agenda for a given time period, which shows everything in my local time, which is fine.
I am having difficulty getting the local time.
When I retrieve the events, the time is shown in my local time.
I can retrieve the timezone in the format Europe/Rome, etc. but this doesn't help me display the local time.
Attached is a screenshot of an entry in my calendar:
And here is how the event is seen from my script (taken from the log file):
Start: 2017-03-29T16:35:00+01:00, startTimeZone: Europe/Berlin.
End: 2017-03-29T22:30:00+01:00, endTimeZone: Asia/Qatar
These times should be Start: 17:35 and End: 00:30, respectively.
Has anyone got any ideas on how to get the local time or convert between timezones?
Hopefully this might help you.
function timezones()
{
var today = new Date();
var hour = 3600000;
var tz = '';
today = new Date(today.getTime() + (13 * hour));
var s = '<div id="mydiv">';
for(var i = 12; i >= -11; i--)
{
if(i > 0){ tz = 'GMT+' + i;}
if(i == 0){tz = 'GMT';}
if(i < 0){tz = 'GMT' + i;}
today = new Date(today.getTime() - hour);
s += '<div class="myDates">' + Utilities.formatDate(today,"GMT", "'Date:'yyyy-MM-dd' Time:'HH:mm:ss") + 'TimeZone; "' + tz + '"</div>';
}
s += '</div>';
dispStatus('Timezones', s);
}
This is the display routine that I use.
function dispStatus(title,html,width,height,modal)
{
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 400;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var modal = typeof(modal) !== 'undefined' ? modal : false;
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
if(!modal)
{
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
else
{
SpreadsheetApp.getUi().showModalDialog(htmlOutput, title);
}
}
And here is a timezone map.
<h1>Calendar Play</h1>
function calendarTesting()
{
var rngA = CalendarApp.getAllOwnedCalendars();
var s='';
for(var i = 0;i < rngA.length; i++)
{
s += '<div id="Cal' + i + '"><Strong>Name: </strong>' + rngA[i].getName();
s += '<br /><strong>Color: </strong><span style="color:'+ 'black' +';">' + rngA[i].getColor() + '</span>';
s += '<br /><strong>Description: </strong>' + rngA[i].getDescription();
var pri = (rngA[i].isMyPrimaryCalendar())? 'Yes': 'No';
s += '<br /><strong>IsMyPrimaryCalender: </strong>' + pri + '</div>';
s += '<style>#Cal'+ i +'{background-color:'+ rngA[i].getColor() +';padding:10px;}</style>';
}
var now = new Date();
var ForWeeksFromNow = new Date(now.getTime() + (28 * 24 * 60 * 60 * 1000));
var events = CalendarApp.getDefaultCalendar().getEvents(now,ForWeeksFromNow);
for(var j = 0; j < events.length; j++)
{
s+= '<div style="border:1px solid black;padding:10px 50px 10px 10px;">';
s += '<div style="float:right;font-size:48px;">' + Utilities.formatDate(events[j].getStartTime(),"GMT-7", "E") + '</div>';
s += '<br /><strong>Title: </strong>' + events[j].getTitle();
s += '<br /><strong>Start: </strong>' + Utilities.formatDate(events[j].getStartTime(),"GMT-7", "MMM dd HH:mm");
s += '<br /><strong>End: </strong>' + Utilities.formatDate(events[j].getEndTime(), "GMT-7", "MMM dd HH:mm");
s += '<div style="float:right;font-size:12px;">' + events[j].getDescription() + '</div>';
s += '</div>';
}
s += '<br /><br /><input type="button" value="Exit" onClick="google.script.host.close();" />';
var title = 'Calendar for: ' + Utilities.formatDate(now, "GMT-7", "E MMM dd, yyyy");
dispStatus(title, '<p>' + s + '</p>',600,500);
}
function dispStatus(title,html,width,height)
{
// Display a modeless dialog box with custom HtmlService content.
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 250;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}

Run a JS function on page load

I know that this question has been asked multiple times, but my case is different. So I have an external JavaScript file which contains the code for my accordion menus (you know, the user clicks on a title and it expands). Now I want to get a # (hash sign) from the url and according to it to open a specific "accordion" onload.
So here's what I've tried:
<body onload="runAccordion(index);"> <!-- In the example bellow, index should be equal to 1 -->
But it never worked (as desired), because I don't know how to "read" the url's # (element's id)...
Here's the markup for an accordion:
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1);">
<div class="AccordionTitle" id="AccordionTitle1">
<p>Title</p>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<p>
<!-- Content -->
</p>
</div>
Or maybe I should use PHP $_GET???
JS file contents:
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
Give the following a try:
$(document).ready(function() {
var hash = window.location.hash;
hash = hash.length > 0 ? hash.substring(1);
if (hash.length) {
runAccordion(window.location.hash);
}
});
The above will grab your hash index out of the URL. To add a hash to the URL, try the following:
window.location.hash = 1; //or whatever your index is
# You can use: #
window.onload = function() {
runAccordion(window.location.hash);
}

Adding Delay between inserting data in row

I am recieving data (10 records at a time) and inserting it in a div in a javascript loop
var a1 = $('.HomeAnnoucement').length;
var a2 = $('.HomeAnnoucement').length;
for (a1 ; a1 < (+a2 + +data.d.length) ; a1++) {
var a = a1 - a2;
var newFormat = '<div class="HomeAnnoucement"><label class="annID" id="archannouncementID' + a1 + '" style="display: none;" /><div class="DateandDelete left"><a class="AnnoucementDate left"><strong>' + data.d[a].EffectiveDate.split('/')[1] + getPostWord(parseInt(data.d[a].EffectiveDate.split('/')[1])) + '</strong> ' + getMonthString(parseInt(data.d[a].EffectiveDate.split('/')[0])) + '</a><div class="clear"></div></div><a class="AnnoucementTitle left"><strong id="archannTitle' + a1 + '" class="bold"></strong></a><div class="clear"></div></div><div class="AnnoucementDescription" id="archannDescription' + a1 + '" style="display:none;"></div>';
$('#archivedAnnouncements').append(newFormat);
$('#archannouncementID' + a1).append(data.d[a].ID);
$('#archannTitle' + a1).append(data.d[a].Title);
if (data.d[a].Owner != "" && data.d[a].Owner != " ") {
$('#archannTitle' + a1).append('<label style="font-weight: normal !important;"> by ' + data.d[a].Owner + '</label>');
}
var description = data.d[a].Description.replace(/\"/g, "'");
var div = document.createElement("div");
div.innerHTML = description;
var descriptiontext = div.textContent || div.innerText || "";
$('#archannDescription' + a1).html(data.d[a].Description);
}
I want to add delay in between inserting the rows. So that the user could see each record insertion in the grid. I have tried inserting the elements with display: none and fadingIn setTimeOut function but that didnt work. Please help.
Use JQuery Show with animation
Here is sample quoted form page above
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Show it</button>
<p style="display: none">Hello 2</p>
<script>
$("button").click(function () {
$("p").show("slow");
});
</script>
</body>
</html>
In this case you can add hidden controls to child list, and call show with animation in loop
JQuery .delay() would help you
http://api.jquery.com/delay/
I've modified your existing code to hide each row and then set a delay and fadeIn...
var a1 = $('.HomeAnnoucement').length;
var a2 = $('.HomeAnnoucement').length;
for (a1 ; a1 < (+a2 + +data.d.length) ; a1++) {
var a = a1 - a2;
var $newFormat = $('<div class="HomeAnnoucement"><label class="annID" id="archannouncementID' + a1 + '" style="display: none;" /><div class="DateandDelete left"><a class="AnnoucementDate left"><strong>' + data.d[a].EffectiveDate.split('/')[1] + getPostWord(parseInt(data.d[a].EffectiveDate.split('/')[1])) + '</strong> ' + getMonthString(parseInt(data.d[a].EffectiveDate.split('/')[0])) + '</a><div class="clear"></div></div><a class="AnnoucementTitle left"><strong id="archannTitle' + a1 + '" class="bold"></strong></a><div class="clear"></div></div><div class="AnnoucementDescription" id="archannDescription' + a1 + '" style="display:none;"></div>');
$('#archivedAnnouncements').append($newFormat);
$('#archannouncementID' + a1).append(data.d[a].ID);
$('#archannTitle' + a1).append(data.d[a].Title);
if (data.d[a].Owner != "" && data.d[a].Owner != " ") {
$('#archannTitle' + a1).append('<label style="font-weight: normal !important;"> by ' + data.d[a].Owner + '</label>');
}
var description = data.d[a].Description.replace(/\"/g, "'");
var div = document.createElement("div");
div.innerHTML = description;
var descriptiontext = div.textContent || div.innerText || "";
$('#archannDescription' + a1).html(data.d[a].Description);
$newFormat.hide().delay(a * 500).fadeIn();
}

Adding javascript loops into SQL database

What i am trying to achieve is adding the javascript loops and the named variables into an sql database, some of them are already added to an external script so work fine however some which i have named in the SQL script at the bottom still need adding, however as the database won't accept a colon ":" they won't enter it and is returning an error, looking at the code at the bottom with replace function im sure you can see what i am trying to achieve but failing miserably, help is much appreciated!
window.status = 'Loading contingency scripts - please wait...';
audit('Loading contingency scripts');
var conting = {
i: 0,
start: function() {
window.status = 'Loading form - please wait...';
var t = '';
t += '<form name="frm_conting" id="frm_conting" onsubmit="return false;">';
t += '<table width="100%" cellspacing="1" cellpadding="0">';
t += '<tr><td>Date (DD/MM/YY):</td><td><input type="text" size="8" value="' + current_date + '" id="date"></td></tr>';
t += '<tr><td>Time Started:</td><td><select id="timefrom"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select></td></tr>';
t += '<tr><td>Time Finished:</td><td><select id="timeto"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select><tr><td>Extension #:</td><td><input type="text" size="5" value="' + my.extension + '" id="staffid"></td></tr>';
t += '<tr><td>Desk ID:</td><td><input type="text" size="5" value=' + my.deskid + ' id="desk"></td></tr>';
t += '<tr><td>Number of calls:</td><td><input type="text" size="5" id="calls"></td></tr>';
t += '<tr><td>Avid ID:</td><td><input type="text" size="5" id="avid"></td></tr>';
t += '<tr><td><input type="button" value="Submit" onClick="conting.save()"></td>';
t += '</table>';
t += '</form>';
div_form.innerHTML = t;
window.resizeTo(400, 385);
window.status = '';
},
save: function() {
var conting_date = frm_conting.date.value;
if (!isdate(conting_date)) {
alert("You have entered an incorrect date.");
return false;
};
var conting_timefrom = frm_conting.timefrom.value;
var conting_timeto = frm_conting.timeto.value;
if (conting_timefrom == '' || conting_timeto == '') {
alert("You need to enter a starting & finishing time.");
return false;
};
if (conting_timefrom > conting_timeto) {
alert("The time you have entered is after the finish time.");
return false;
};
var conting_staffid = frm_conting.staffid.value;
if (conting_staffid.length != 5) {
alert("You have entered an incorrect extension number.");
return false;
};
var conting_desk = frm_conting.desk.value;
if (conting_desk.length != 5) {
alert("You have entered an incorrect desk ID.");
return false;
};
var conting_calls = frm_conting.calls.value;
if (isNaN(conting_calls)) {
alert("You have not entered amount of calls.");
return false;
};
var conting_avid = frm_conting.avid.value;
if (isNaN(conting_avid)) {
alert("You have entered an incorrect avid ID.");
return false;
};
if (conting_avid.length != 5) {
alert("You have entered an incorrect avid ID.");
return false;
};
conn.open(db["contingency"]);
rs.open("SELECT MAX(prac_id) FROM practice", conn);
var prac_id = rs.fields(0).value + 1;
var prac_timefrom = parseFloat(frm_conting.timefrom.value);
var prac_timeto = parseFloat(frm_conting.timefrom.value);
var prac_calls = frm_conting.calls.value;
var prac_avid = frm_conting.avid.value;
rs.close();
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
conn.close();
}
};
window.status = '';​
This bit of code looks extremely dubious.
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
you should use parameterised queries to avoid SQL injection. Additionally even without any deliberate SQL injection attempts this code will fail if any of the form fields contain the ' character.
You are assigning to the variable q twice and aren't executing the result of the first assignment. (And declaring it twice actually?!)
There is no syntax such as UPDATE SELECT it would need to be something like UPDATE practice SET SomeColumn = REPLACE (SomeColumn, 'isNaN', 'isNull') presumably except see 4 and 5.
I'm not clear what the Replace is meant to be doing anyway. What are the 3 parameters you have given it?
It would be better to do the Replace on the value before inserting into the database rather than inserting it wrong then updating it to the new value.

Categories

Resources