Add space/new line between elements with javascript - javascript

So I am attempting to display all the questions and responses from my Firebase database. It is showing up fine, but it looks ugly, because there is no space between the question and responses. I've tried using the createElement feature as well as .innerHTML to add a nonbreaking space. Nothing is working. Here is the code I have thus far: Thanks for your help!
<button id="all" onclick="button()"> View All </button>
<h4> All Users: </h4>
<script>
function button(){
var userRef = new Firebase("https://speedpoll-1fd08.firebaseio.com");
userRef.on("value", function(snapshot) {
// The callback function will get called twice, once for "fred" and once for "barney"
snapshot.forEach(function(childSnapshot) {
// key will be "fred" the first time and "barney" the second time
var key = console.log(childSnapshot.key());
// childData will be the actual contents of the child
// var userInfo = console.log(childSnapshot.val());
var element = document.getElementById("viewAll");
var para = document.createElement("h5");
var node = document.createTextNode("Question: " + childSnapshot.key());
console.log(childSnapshot.child("Option1").child('Response1').val());
var node1= document.createTextNode("Response 1: " + childSnapshot.child("Option1").child('Response1').val());
//var space = document.createElement(" ");
element.innerHTML += " ";
var node2= document.createTextNode("Response 2: " + childSnapshot.child('Option2').child('Response2').val());
var node3= document.createTextNode("Response 3: " + childSnapshot.child('Option3').child('Response3').val());
para.appendChild(node);
//para.appendChild(space);
para.appendChild(node1);
para.appendChild(node2);
para.appendChild(node3);
element.appendChild(para);
});
});
}
</script>
<div id="viewAll">
</div>

You can add a line by adding an <hr> element, as explained here: http://www.htmlgoodies.com/tutorials/getting_started/article.php/3479441
Like this one:
You can also add <div> sections for each element, and style the margins, paddings and borders with CSS. The same for <p> sections.
You can play around with this JSFiddle:
http://jsfiddle.net/jmgomez/n0e1ev8e/
Check this out also on how to style borders with CSS: http://www.w3schools.com/css/css_border.asp

Related

Losing CSS styling upon printing

I am using a style sheet to properly print out a webpage. The webpage has fields sat next to each other but upon printing these fields no longer sit next to each other but instead cascade down the sheet. I have created a style sheet but I'm not sure exactly how that is supposed to stop this from happening unless I hard code into the style sheet what I want to happen. Unfortunately I can't do that because I need to print out several different pages that have different layouts.
Is there any way to fix this?
function removeLinks(printDiv) {
var all_links = document.getElementById(printDiv).getElementsByTagName("a");
for (var i = 0; i < all_links.length; i++) {
all_links[i].removeAttribute("href");
}
}
function printdiv(printDiv) {
var divCaseNote = document.getElementById(printDiv);
var oldstr = document.body.innerHTML;
var oldTitle = document.title;
if (divCaseNote != null) {
divCaseNote.style = "padding: 20px;";
innerHTML = divCaseNote.innerHTML;
}
removeLinks(printDiv);
var headstr = "<html><head rel=\"stylesheet\" media=\"all\" link href=\"/CSS/style.css\"/><title> </title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printDiv).innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
document.title = oldTitle.replace(" - View Case Note", "");
window.print()
document.body.innerHTML = oldstr;
document.title = oldTitle;
EDIT: A snippet of the html output of this function. It holds all the correct divs for the columns but instead of printing the columns side by side they print cascading down the page.
<div class=\"view-value\" style=\"border-left: none;\">
Jerry</div></div></div>
<div class=\"col-md-3\"><div class=\"media-body\">
<div class=\"view-label\">Participant's Last Name</div>
<div class=\"view-value\" style=\"border-left: none;\">Field</div>
What it should look like
[
What it actually looks like after printing
The problem is that the inline styles are getting obliterated by this statement:
divCaseNote.style = "padding: 20px;";
which removes all the style attribute and replaces it with just the padding.
To add/alter the padding but nothing else you want to change just that property so try:
divCaseNote.style.padding = "20px";

Data returns correctly but won't display the returned data properly?

So I'm currently struggling to view the returned data in a p and textarea element.
Here's the function I'm using, you can see that I am receiving each key from the comments node and getting the comment title and message and that works as it should...
function loadComments() {
var comments =
firebase.database().ref('/comments').once('value', function(snapshot) {
snapshot.forEach(function(data) {
var childData = data.val();
var childKey = data.key;
console.log(childData.title + " " + childData.message);
Elements.commentTitle.text(childData.title);
Elements.commentMessage.text(childData.message);
var clonedNode = $('.listItems:last').clone();
$(clonedNode).insertAfter('.listItems:last');
$(clonedNode).css({
display: "block"
});
});
});
}
However when i try to view the data in the 2 elements, It will only show the title and message from the first node and that will duplicate depending on how many comments have been sent.
So for example, If say there were 5 comments, all with different data, so title and message were different. This is what you will see...
Title
Message
Title
Message
Title
Message
Title
Message
Title
Message
Also just in case it helps, here is the html code I'm using....
<div class="container listItems text-left w-75 justify-content-center" style="display: none">
<p class="titleBody"><strong></strong></p>
<ul><p class="commentBody"></p></ul>
</div>
The problem is that you clone existing element. You should replace data right after element has been cloned.
Code below fixes the problem you complained about.
function loadComments() {
var comments =
firebase.database().ref('/comments').once('value', function(snapshot) {
snapshot.forEach(function(data) {
var childData = data.val();
var childKey = data.key;
var clonedNode = $('.listItems:first-child').clone();
clonedNode.find('.titleBody:first-child > strong:first-child').text(childData.title);
clonedNode.find('.commentBody:first-child').text(childData.message);
clonedNode.insertAfter('.listItems:last-child');
clonedNode.css({
display: "block"
});
});
});
}

LocalStorage and adding li to list

I'm trying to make a small script that allows for a little notes section. This section would have an input box that allows for adding elements to the list; which will be saved in localStorage so they are not lost when I refresh or close the browser. The code I have is as follows (it's all done through JS even the html, but ignore that.)
var notes = [];
var listthings = "<h2 id=\"titlething\">Notes</h2>" +
"<ul id=\"listing\">" +
"</ul>"
"<input type=\"text\" name=\"item\" id=\"textfield\">" +
"<input type=\"submit\" id=\"submitthing\" value=\"Submit\">";
JSON.parse(localStorage.getItem('notes')) || [].forEach( function (note) {
"<li id=\"listitem\">" + notes + "</li>";
})
$('#submitthing').click(function() {
notes.push($('#textfield').val());
});
localStorage.setItem('notes', JSON.stringify(notes));
Also, how would I go about appending the latest added li between the opening and closing tag? Obviously I'd usually do it using jQuery, but this is puzzling me a little. However, only the 'Notes' loads at the top, any ideas?
Your approach is way off the mark. You don't need JSON at all (this just confuses things) and you don't need to manually create HTML.
Also, you can use an array to store the notes, but since localStorage is the storage area, so an array is redundant. Additionally, without using an array, you don't need JSON. The entire problem becomes much easier to solve.
Unfortunately, the following won't run here in this snippet editor, due to security issues, but it would do what you are asking. This fiddle shows it working: https://jsfiddle.net/Lqjwbn1r/14/
// Upon the page being ready:
window.addEventListener("DOMContentLoaded", function(){
// Get a reference to the empty <ul> element on the page
var list = document.getElementById("notes");
// Loop through localStorage
for (var i = 0; i < localStorage.length; i++){
// Make sure that we only read the notes from local storage
if(localStorage.key(i).indexOf("note") !== -1){
// For each item, create a new <li> element
var item = document.createElement("li");
// Populate the <li> with the contents of the current
// localStorage item's value
item.textContent = localStorage.getItem(localStorage.key(i));
// Append the <li> to the page's <ul>
list.appendChild(item);
}
}
// Get references to the button and input
var btn = document.getElementById("btnSave");
var note = document.getElementById("txtNote");
// Store a note count:
var noteCount = 1;
// When the button is clicked...
btn.addEventListener("click", function(){
// Get the value of the input
var noteVal = note.value;
// As long as the value isn't an empty string...
if(noteVal.trim() !== ""){
// Create the note in localStorage using the
// note counter so that each stored item gets
// a unique key
localStorage.setItem("note" + noteCount, noteVal);
// Create a new <li>
var lstItem = document.createElement("li");
// Set the content of the <li>
lstItem.textContent = noteVal;
// Append the <li> to the <ul>
list.appendChild(lstItem);
// Bump up the note counter
noteCount++;
}
});
});
<input type=text id=txtNote><input type=button value=Save id=btnSave>
<ul id=notes></ul>
This is how I would approach it using jquery. but depens how complex this should be. this is just simple demo.
<input type="text" id="note" />
<button id="add">add note</button>
<ul id="notes"></ul>
javascript and jquery
function addNote(){
var data = localStorage.getItem("notes")
var notes = null;
if(data != null)
{
notes = JSON.parse(data);
}
if(notes == null){
notes = [];
}
notes.push($("#note").val());
localStorage.setItem("notes", JSON.stringify(notes));
refreshNotes();
}
function refreshNotes(){
var notesElement =$("#notes");
notesElement.empty();
var notes = JSON.parse(localStorage.getItem("notes"));
for(var i = 0; i< notes.length; i++){
var note = notes[i];
notesElement.append("<li>"+note+"</li>");
}
}
$(function(){
refreshNotes();
$("#add").click(function(){
addNote();
});
})
example:
http://codepen.io/xszaboj/pen/dOXEey?editors=1010

Restore exact innerHTML to DOM

I'd like to save the html string of the DOM, and later restore it to be exactly the same. The code looks something like this:
var stringified = document.documentElement.innerHTML
// later, after serializing and deserializing
document.documentElement.innerHTML = stringified
This works when everything is perfect, but when the DOM is not w3c-comliant, there's a problem. The first line works fine, stringified matches the DOM exactly. But when I restore from the (non-w3c-compliant) stringified, the browser does some magic and the resulting DOM is not the same as it was originally.
For example, if my original DOM looks like
<p><div></div></p>
then the final DOM will look like
<p></p><div></div><p></p>
since div elements are not allowed to be inside p elements. Is there some way I can get the browser to use the same html parsing that it does on page load and accept broken html as-is?
Why is the html broken in the first place? The DOM is not controlled by me.
Here's a jsfiddle to show the behavior http://jsfiddle.net/b2x7rnfm/5/. Open your console.
<body>
<div id="asdf"><p id="outer"></p></div>
<script type="text/javascript">
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
var e = document.getElementById('asdf')
console.log(e.innerHTML);
e.innerHTML = e.innerHTML;
console.log(e.innerHTML); // This is different than 2 lines above!!
</script>
</body>
If you need to be able to save and restore an invalid HTML structure, you could do it by way of XML. The code which follows comes from this fiddle.
To save, you create a new XML document to which you add the nodes you want to serialize:
var asdf = document.getElementById("asdf");
var outer = document.getElementById("outer");
var add = document.getElementById("add");
var save = document.getElementById("save");
var restore = document.getElementById("restore");
var saved = undefined;
save.addEventListener("click", function () {
if (saved !== undefined)
return; /// Do not overwrite
// Create a fake document with a single top-level element, as
// required by XML.
var parser = new DOMParser();
var doc = parser.parseFromString("<top/>", "text/xml");
// We could skip the cloning and just move the nodes to the XML
// document. This would have the effect of saving and removing
// at the same time but I wanted to show what saving while
// preserving the data would look like
var clone = asdf.cloneNode(true);
var top = doc.firstChild;
var child = asdf.firstChild;
while (child) {
top.appendChild(child);
child = asdf.firstChild;
}
saved = top.innerHTML;
console.log("saved as: ", saved);
// Perform the removal here.
asdf.innerHTML = "";
});
To restore, you create an XML document to deserialize what you saved and then add the nodes to your document:
restore.addEventListener("click", function () {
if (saved === undefined)
return; // Don't restore undefined data!
// We parse the XML we saved.
var parser = new DOMParser();
var doc = parser.parseFromString("<top>" + saved + "</top>", "text/xml");
var top = doc.firstChild;
var child = top.firstChild;
while (child) {
asdf.appendChild(child);
// Remove the extra junk added by the XML parser.
child.removeAttribute("xmlns");
child = top.firstChild;
}
saved = undefined;
console.log("inner html after restore", asdf.innerHTML);
});
Using the fiddle, you can:
Press the "Add LadyGaga..." button to create the invalid HTML.
Press "Save and Remove from Document" to save the structure in asdf and clear its contents. This prints to the console what was saved.
Press "Restore" to restore the structure that was saved.
The code above aims to be general. It would be possible to simplify the code if some assumptions can be made about the HTML structure to be saved. For instance blah is not a well-formed XML document because you need a single top element in XML. So the code above takes pains to add a top-level element (top) to prevent this problem. It is also generally not possible to just parse an HTML serialization as XML so the save operation serializes to XML.
This is a proof-of-concept more than anything. There could be side-effects from moving nodes created in an HTML document to an XML document or the other way around that I have not anticipated. I've run the code above on Chrome and FF. I don't have IE at hand to run it there.
This won't work for your most recent clarification, that you must have a string copy. Leaving it, though, for others who may have more flexibility.
Since using the DOM seems to allow you to preserve, to some degree, the invalid structure, and using innerHTML involves reparsing with (as you've observed) side-effects, we have to look at not using innerHTML:
You can clone the original, and then swap in the clone:
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var clone = e.cloneNode(true);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
snippet.log("2: " + e.innerHTML);
e.parentNode.replaceChild(clone, e);
e = clone;
snippet.log("3: " + e.innerHTML);
Live Example:
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var clone = e.cloneNode(true);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
snippet.log("2: " + e.innerHTML);
e.parentNode.replaceChild(clone, e);
e = clone;
snippet.log("3: " + e.innerHTML);
<div id="asdf">
<p id="outer">
<div>ladygaga</div>
</p>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note that just like the innerHTML solution, this will wipe out event handlers on the elements in question. You could preserve handlers on the outermost element by creating a document fragment and cloning its children into it, but that would still lose handlers on the children.
This earlier solution won't apply to you, but may apply to others in the future:
My earlier solution was to track what you changed, and undo the changes one-by-one. So in your example, that means removing the insert element:
var e = document.getElementById('asdf')
console.log("1: " + e.innerHTML);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
var outer = document.getElementById('outer');
outer.appendChild(insert);
console.log("2: " + e.innerHTML);
outer.removeChild(insert);
console.log("3: " + e.innerHTML);
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
var outer = document.getElementById('outer');
outer.appendChild(insert);
snippet.log("2: " + e.innerHTML);
outer.removeChild(insert);
snippet.log("3: " + e.innerHTML);
<div id="asdf">
<p id="outer">
<div>ladygaga</div>
</p>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Try utilizing Blob , URL.createObjectURL to export html ; include script tag in exported html which removes <div></div><p></p> elements from rendered html document
html
<body>
<div id="asdf">
<p id="outer"></p>
</div>
<script>
var insert = document.createElement("div");
var text = document.createTextNode("ladygaga");
insert.appendChild(text);
document.getElementById("outer").appendChild(insert);
var elem = document.getElementById("asdf");
var r = document.querySelectorAll("[id=outer] ~ *");
// remove last `div` , `p` elements from `#asdf`
for (var i = 0; i < r.length; ++i) {
elem.removeChild(r[i])
}
</script>
</body>
js
var e = document.getElementById("asdf");
var html = e.outerHTML;
console.log(document.body.outerHTML);
var blob = new Blob([document.body.outerHTML], {
type: "text/html"
});
var objUrl = window.URL.createObjectURL(blob);
var popup = window.open(objUrl, "popup", "width=300, height=200");
jsfiddle http://jsfiddle.net/b2x7rnfm/11/
see this example: http://jsfiddle.net/kevalbhatt18/1Lcgaprc/
MDN cloneNode
var e = document.getElementById('asdf')
console.log(e.innerHTML);
backupElem = e.cloneNode(true);
// Your tinkering with the original
e.parentNode.replaceChild(backupElem, e);
console.log(e.innerHTML);
You can not expect HTML to be parsed as a non-compliant HTML. But since the structure of compiled non-compliant HTML is very predictable you can make a function which makes the HTML non-compliant again like this:
function ruinTheHtml() {
var allElements = document.body.getElementsByTagName( "*" ),
next,
afterNext;
Array.prototype.map.call( allElements,function( el,i ){
if( el.tagName !== 'SCRIPT' && el.tagName !== 'STYLE' ) {
if(el.textContent === '') {
next = el.nextSibling;
afterNext = next.nextSibling;
if( afterNext.textContent === '' ) {
el.parentNode.removeChild( afterNext );
el.appendChild( next );
}
}
}
});
}
See the fiddle:
http://jsfiddle.net/pqah8e25/3/
You have to clone the node instead of copying html. Parsing rules will force the browser to close p when seeing div.
If you really need to get html from that string and it is valid xml, then you can use following code ($ is jQuery):
var html = "<p><div></div></p>";
var div = document.createElement("div");
var xml = $.parseXML(html);
div.appendChild(xml.documentElement);
div.innerHTML === html // true
You can use outerHTML, it perseveres the original structure:
(based on your original sample)
<div id="asdf"><p id="outer"></p></div>
<script type="text/javascript">
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
var e = document.getElementById('asdf')
console.log(e.outerHTML);
e.outerHTML = e.outerHTML;
console.log(e.outerHTML);
</script>
Demo: http://jsfiddle.net/b2x7rnfm/7

Hover over data using title attribute in javascript

I have a javascript code that displays data in a table format and when hovered over the first column it displays additional details. The hover over code is using jquery tooltip and the title attribute of html. The code works fine in most cases but if one of the fields I am displaying in the hover has " symbol it screws up everything that record onwards and the hover and main data display together and the hover doesnt work on those rows.
below is a snapshot of my code
var medicationName = medJSON.MED_DETAILS[medIdx1].ORDER_NAME;
var orderdetails = medJSON.MED_DETAILS[medIdx1].ORD_DETAILS;
var comments = medJSON.MED_DETAILS[medIdx1].ORD_COMMENTS;
var reqStart = medJSON.MED_DETAILS[medIdx1].REQ_ST_DT;
var originalStart = medJSON.MED_DETAILS[medIdx1].ORIG_ORD_DT;
var lastDose = medJSON.MED_DETAILS[medIdx1].LAST_DOSE;
var nextDose = medJSON.MED_DETAILS[medIdx1].NEXT_DOSE;
var stopDt = medJSON.MED_DETAILS[medIdx1].STOP_DT_TM;
var stopReason = medJSON.MED_DETAILS[medIdx1].STOP_REASON;
var enteredBy = medJSON.MED_DETAILS[medIdx1].ORDER_ENTERED_BY;
var status = medJSON.MED_DETAILS[medIdx1].ORD_STATUS;
var simpleDetails = medJSON.MED_DETAILS[medIdx1].CLIN_DISP_LN;
if(nextDose.length == 0)
{
nextDose = "Not Defined";
}
var medHover = ["<table><tr><td><b>Medication:</b></td><td>",medicationName,"</td></tr>"
,"<tr><td><b>Details:</b></td><td>",simpleDetails,"</td></tr>"
//,"<tr><td><b>Order Comments:</b></td><td>",comments,"</td></tr>"
,"<tr><td><b>Request Start:</b></td><td>",reqStart,"</td></tr>"
,"<tr><td width = 200px><b>Original Order Date/Time:</b></td><td>",originalStart,"</td></tr>"
,"<tr><td><b>Last Documented Dose:</b></td><td>",lastDose,"</td></tr>"
,"<tr><td><b>Next Scheduled Dose:</b></td><td>",nextDose,"</td></tr>"
,"<tr><td><b>Stop Date/Time:</b></td><td>",stopDt,"</td></tr>"
,"<tr><td><b>Stop Reason:</b></td><td>",stopReason,"</td></tr>"
,"<tr><td><b>Order Entered By:</b></td><td>",enteredBy,"</td></tr>"
,"<tr><td><b>Status:</b></td><td>",status,"</td></tr>"
,"</table>"]
tempStr1.push("<tr class = 'evenrow' ><td class = 'cmedname custhvr' title=\"",medHover.join(""),"\">",medicationName,"</td><td> ",simpleDetails,"</td></tr>")
thanks,
Sid
Process medHover with:
medHover.join("").replace('\"', '"');
This replaces the quote character with a value usable with HTML.

Categories

Resources