Inserting an element right after the sibling in Javascript - javascript

I'm making a posting system that when the user types in a message, it creates a few elements and puts it below the "robot" chat message. If the user inputs two different messages, the latest input message goes above the other user message. I want them to go from top to bottom in chronological order.
This doesn't seem to work: (the if/else part)
function submitUserMessage(){
var message = document.getElementById("user-input");
if(message.value){
// YOU
var you = document.createElement("h4");
var youText = document.createTextNode("You");
you.appendChild(youText);
you.className = "ytitle";
document.body.appendChild(you);
insertAfter(robotSays, you);
// User's message
var userMessage = document.createElement("span");
var userMessageText = document.createTextNode(message.value);
userMessage.appendChild(userMessageText);
userMessage.className = "umsg";
document.body.appendChild(userMessage);
insertAfter(you, userMessage);
} else if(userMessage){
userMessage.nextSibling.insertAfter(this);
}
}
Here's a fiddle of my post system :: http://jsfiddle.net/MatthewKosloski/YWWMW/
(Use the enter key to submit)

var userMessage = robotSays;
function submitUserMessage(){
var message = document.getElementById("user-input");
if(message.value){
// YOU
var you = document.createElement("h4");
var youText = document.createTextNode("You");
you.appendChild(youText);
you.className = "ytitle";
document.body.appendChild(you);
insertAfter(userMessage, you);
// User's message
userMessage = document.createElement("span");
var userMessageText = document.createTextNode(message.value);
userMessage.appendChild(userMessageText);
userMessage.className = "umsg";
document.body.appendChild(userMessage);
insertAfter(you, userMessage);
}
}

Related

getChild of body of gmail email using Goole Apps Scripts (GAS)

Problem
I have automated emails coming to me with particular client details in them. I have the repetitive task of repling to each email with a template. I am wanting to automate the process utilising Google Apps Scripts.
Where I'm up to
I have worked out how to collect the body of the email I am replying to. I'm trying to get the third paragraph info and store this in a variable.
Here is my code:
function autoReply() {
//Capturing the automated email
var queryInbox = "is:unread from:(example#gmail.com)";
var locatedEmail = GmailApp.search(queryInbox);
for (var i in locatedEmail){
var thread = locatedEmail[i];
var messages = thread.getMessages();
var msgBody = messages[i].getBody();
var clientsEmail = msgBody.getChild('p')[3]; //Attempting to obtain the third paragraph of the body.
if(messages.length === 1) {
var body = "<p> The clients email is: " + clientsEmail + "</p>";
};
var options = { name: "Temp Name",htmlBody: body };
thread.reply(body, options);
thread.markRead();
thread.moveToArchive();
}
};
Note: Img attached for context.
I believe your goal as follows.
When the thread has one message, you want to retrieve the body of email.
You want to retrieve the 3rd paragraph from the message of email.
You want to reply the message including the retrieved 3rd paragraph.
Modification points:
At for (var i in unread){, I thought that you might use locatedEmail.
When you want to reply the message with messages.length === 1, var msgBody = messages[i].getBody(); is required to be modified. Because in your for loop, the index i is used for var thread = locatedEmail[i]; and var msgBody = messages[i].getBody();.
In your case, I think that getPlainBody() instead of getBody() might be suitable.
When above points are reflected to your script, it becomes as follows.
Modified script:
function autoReply() {
var queryInbox = "is:unread from:(example#gmail.com)";
var locatedEmail = GmailApp.search(queryInbox);
locatedEmail.forEach(thread => {
var messages = thread.getMessages();
if (messages.length === 1) {
var msgBody = messages[0].getPlainBody();
var clientsEmail = msgBody.split("\n")[2]; // Here, the 3rd paragraph is retrieved.
var body = "<p> The clients email is: " + clientsEmail + "</p>";
var options = { name: "Temp Name",htmlBody: body };
thread.reply(body, options);
thread.markRead();
thread.moveToArchive();
}
});
}
Reference:
getPlainBody()

Can not append a div after Axios Call

I have looked up previous questions asked on this forum and I did not find anything that is relevant to this specific situation. I am trying to create a user card from data I am pulling from Github. When I try to append the fist child div to the parent div that exists in the HTML my code throws the following error "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'." Problem is it definitely IS a node. Here is my code.
//Axios call
const info = axios.get(url).then(({ data }) => createCard(data));
function createCard(gitHubData) {
const cards = document.querySelector(".cards");
//Creating the elements for the cards
const card = document.createElement("div").classList.add("card");
var img = document.createElement("img");
const info = document.createElement("div").classList.add("card-info");
var name = document.createElement("h3").classList.add("name");
var username = document.createElement("p").classList.add("username");
var location = document.createElement("p");
var profile = document.createElement("p");
var followers = document.createElement("p");
var following = document.createElement("p");
var bio = document.createElement("p");
//Creating the nested layout of our elements
cards.appendChild(card); //code fails here
card.appendChild(img);
card.appendChild(info);
info.appendChild(name);
info.appendChild(username);
info.appendChild(location);
info.appendChild(profile);
info.appendChild(followers);
info.appendChild(following);
info.appendChild(bio);
//Assigning the cards to info collected from axios
img.src = gitHubData.avatar_url;
console.log(img.src);
name = gitHubData.name; //If I use .innerHTML or .textContent returns
//undefined
console.log(name);
username = gitHubData.login;
location = gitHubData.location;
profile = `Profile: ${gitHubData.html_url}`;
followers = gitHubData.followers;
following = gitHubData.following;
bio = gitHubData.bio;
return cards;
}
I am still not sure why my code failed in the first place but I shut down my computer for the night and tried again in the morning. The correct code (which I tried before unsuccessfully was the following:
name.textContent = gitHubData.name;
username.textContent = gitHubData.login;
location.textContent = gitHubData.location;
profile.textContent = `Profile: ${gitHubData.html_url}`;
followers.textContent = gitHubData.followers;
following.textContent = gitHubData.following;
bio.textContent = gitHubData.bio;

Function works as expected when called from function using XMLHttpRequest, but fails when called from a function using EventSource. Why is this?

I'm working on creating a basic messenger using Javascript. I have three functions in a separate js file called loadMessage, messageListener, and displayMessage.
The function loadMessage makes a call to my database for all existing messages, and then calls displayMessages to construct some divs which I use to show the messages I got from the server. These divs are created to appear under each other, with the bottom div being the newly created one showing the latest message.
Once all the messages have been created loadMessage then calls messageListener. This function 'listens' for any new messages which might appear on the database. If any appear then messageListener calls displayMessage. I expect this to create a new div at the bottom of my other divs as before, however when it calls displayMessage the behaviour is completely different than when loadMessage calls displayMessage.
Specifically, it does not create a new div but instead just changes the text in an existing div which appears anywhere within the newly created divs (for example, the div which displays the first message or one somewhere in the middle).
My HTML and PHP files all behave as expected, so I think my issue is somewhere in these three functions.
How can I fix this to behave as expected?
Code:
// Loads chat messages history and listens for upcoming ones.
function loadMessages(userID, contactID) {
contactIDGlobal = contactID;
//load existing messages
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var param = "userID="+userID+"&contactID="+contactID+"&date="+date;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Interface-getMessage.php?", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(param);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//retrives a string of all past messages
var messageString = xmlhttp.responseText;
//parse string to get messages.
var parseMessageString = messageString.split('-');
for (var i = 0; parseMessageString[i] !== null && parseMessageString[i] !== ''; i = i+5){
var contactID = parseMessageString[i];
var senderID = parseMessageString[i+1];
var message = parseMessageString[i+2];
var time = parseMessageString[i+3];
var mID = parseMessageString[i+4];
displayMessage(userID, senderID, contactID, message, date, time, mID);
}
}
};
//listen for new messages
messageListener(userID, contactID);
}
function messageListener(userID, contactID){
if(typeof(EventSource)!=="underfined") {
var newMessage = new EventSource("testerfile.php?userID="+userID+"&contactID="+contactID);
newMessage.onmessage = function(event) {
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3];
var time = parseNewMessage[4];
var messageID = parseNewMessage[5];
console.log(event.data);
displayMessage(userID, senderID, contactID, message, date, time, messageID);
};
}else {
document.getElementById("messages").innerHTML = "Your browser does not support this";
}
}
// Displays a Message in the UI.
function displayMessage(userID, senderID, contactID, nMessage, date, time, id){
var messageListElement = document.getElementById('messages');
var messageInputElement = document.getElementById('message');
// If an element for this message already exists, then get it
var id = id;
var div = document.getElementById(id);
// If an element for that message does not exists yet we create it.
if (!div) {
var container = document.createElement('div');
if (userID == senderID){
container.innerHTML = SENDER_MESSAGE_TEMPLATE;
}else{
container.innerHTML = MESSAGE_TEMPLATE;
}
div = container.firstChild;
div.setAttribute('id', id);
for (var i = 0; i < messageListElement.children.length; i++) {
var child = messageListElement.children[i];
}
messageListElement.insertBefore(div, child);
}
var messageElement = div.querySelector('.message');
messageElement.textContent = nMessage;
// Replace all line breaks by <br>.
messageElement.innerHTML = messageElement.innerHTML.replace(/\n/g, '<br>');
}
// Template for messages.
var SENDER_MESSAGE_TEMPLATE =
'<div class="sender_message-container">' +
'<div class="message"></div>' +
'</div>';
var MESSAGE_TEMPLATE =
'<div class="message-container">' +
'<div class="message"></div>' +
'</div>';
The problem was coming from the date being returned as y-m-d, and the parser using "-". This mean I was creating a time var which was the month of my date, and the message ID as the day. I made the alteration below to fix this...
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3]+"-"+parseNewMessage[4]+"-"+parseNewMessage[5];
var time = parseNewMessage[6];
var messageID = parseNewMessage[7];

Trying to understand getThreads in GAS

I am new to app script and I am trying to read an email from my inbox. I thought that getThreads would do the job but I still don't fully understand how to use it. When I try to execute the code I wrote below it comes up with a null error.
Looking at the documentation of getThreads(), they use the example:
// Log the subject lines of the threads labeled with MyLabel
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
Logger.log(threads[i].getFirstMessageSubject());
}
what does "MyLabel" stand for?
This is the code i tried that failed
function myFunction() {
var label = GmailApp.getUserLabelByName('bobtheman#gmail.com');
var threads = label.getThreads();
for (var t in threads) {
var thread = threads[t];
// Gets the message body
var message = thread.getMessages()[0].getPlainBody();
}
GmailApp.sendEmail('barbrabat#gmail.com', 'hola', message)
}
MyLabel is the label of the email. It depends whether you added a label to a specific email or not. You can use the search method instead.
function myFunction(){
var label = 'yourLabel'; // if no label, remove the label in search
// it would be better if you add a label to a specific email for fast and more precise searching
var searchEmail = GmailApp.search('from:me subject:"' + subject + '" label:' + label + '');
var threadId = searchEmail[0].getId(); // get the id of the search email
var thread = GmailApp.getThreadById(threadId); // get email thread using the threadId
var emailMsg = thread.getMessages()[0]; // get the content of the email
var emailContent = emailMsg.getPlainBody(); // get the body of the email
// check using log
Logger.log(emailContent);
// how to open log
// Ctrl + Enter
// Run this function before checking the log
}
Thanks

Why won't my Google Calendar Script run?

I am using Google Script to create a form that will create an event, as you can see from the code I have used two panels. I want to create multiple event forms on the 'parent' panel, I am trying to use the 'child' to hold information about the event. I want to run createEvent() on each child panel, but when I run it the script will not run and show this error message:
"Error occured: InternalError: Cannot find method createEvent((class),(class),(class),object)."
function doGet(){
var app = UiApp.createApplication().setTitle('Create Events');
//Create a penel which holds all the form elelemnts
var parent = app.createHorizontalPanel().setId('parent');
var panelOne = app.createVerticalPanel().setBorderWidth(2);
var eventTitleLabel = app.createLabel('Event Title:');
var eventTitle = app.createTextBox();
var eventStartDateLabel = app.createLabel('Event Start Date:');
var evenStartDate = app.createDateBox();
var eventEndDateLabel = app.createLabel('Event End Date:');
var evenEndDate = app.createDateBox();
var eventDeatilLabel = app.createLabel('Event Details:');
var eventDetail = app.createTextArea().setSize('150', '100');
var eventButton = app.createButton('Create Events');
var cancelButton = app.createButton('Cancel');
panelOne.add(eventTitleLabel)
.add(eventTitle)
.add(eventStartDateLabel)
.add(evenStartDate)
.add(eventEndDateLabel)
.add(evenEndDate)
.add(eventDeatilLabel)
.add(eventDetail)
.add(eventButton)
.add(cancelButton);
var eventHandler = app.createServerClickHandler('createEvents');
eventHandler.addCallbackElement(parent);
//Add this handler to the button
eventButton.addClickHandler(eventHandler);
parent.add(panelOne);
app.add(parent);
app.close();
return app;
}
function createEvents(e){
//Get the active application
var app = UiApp.getActiveApplication();
try{
var eventTitle = e.parameter.eventTitle;
var eventStartDate = e.parameter.eventStartDate;
var eventEndDate = e.parameter.eventEndDate;
var eventDetails = e.parameter.eventDetail;
var cal = CalendarApp.getDefaultCalendar();
cal.createEvent(eventTitle, eventStartDate,eventEndDate,{description:eventDetails});
app.add(app.createLabel('Event created Successfully'));
app.getElementById('panel').setVisible(false);
return app;
}
catch(e){
app.add(app.createLabel('Error occured: '+e));
return app;
}
}
All the input widgets need a .setName() to be able to pass their values to the server function. https://developers.google.com/apps-script/guides/ui-service#ServerHandlers
Also consider using Logger.log() for debugging.
You simply forgot to set names to the widgets you want to get data from... in your example :
var eventTitleLabel = app.createLabel('Event Title:');
var eventTitle = app.createTextBox().setName('eventTitle');
var eventStartDateLabel = app.createLabel('Event Start Date:');
var evenStartDate = app.createDateBox().setName('evenStartDate');
var eventEndDateLabel = app.createLabel('Event End Date:');
var evenEndDate = app.createDateBox().setName('evenEndDate');
var eventDeatilLabel = app.createLabel('Event Details:');
var eventDetail = app.createTextArea().setSize('150', '100').setName('eventDetail');

Categories