Create an Array in For loop without running over the array - javascript

I'm trying to do a college project.
I'm supposed to create 'Notes' add them to an array and keep them in my local storage.
Now the notes should be created with a Fade in effect (transition) using CSS3.
Everything works perfectly until I create the second note at which point my whole array is run over again which makes all the notes to appear in fade.
CSS:
.note_input {
height:255px;
width:200px;
background-image:url('../img/notebg.png');
padding-top:25px;
padding-left:10px;
display:inline-block;
animation: fadein 0.3s;
-webkit-animation: fadein 0.3s;
}
#keyframes fadein {
from {
opacity:0;
}
to {
opacity:1;
}
}
#-webkit-keyframes fadein {
from {
opacity:0;
}
to {
opacity:1;
}
}
And this is my JS to create the Array + Note itself:
function AddNote (){
var input = document.getElementById("txt").value;
var date = d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();
var time = d.getHours() + ":" + d.getMinutes();
var n = new NoteCrt(input,time,date);
notes.push(n);
Note();
}
function Note(){
var note_d = "<div>";
for (var i = 0 ; i < notes.length ; i++) {
note_d += "<span id='fade' class='note_input'>" + "<div class='flow' ><p>"+notes[i].input+"</p></div></br>" + "</br>" +"Time: "+ notes[i].time + "</br>" +"Date: "+ notes[i].date;
note_d += "</span>";
}
note_d += "</div>";
document.getElementById("note_div").innerHTML = note_d;
notes_j = JSON.stringify(notes, null, " ");
localStorage.setItem("NOTE",notes_j);
notes_p = JSON.parse(notes_j);
console.log(notes_p);
}
What happens is that all the notes that are present are recreated with a fade in effect every time...
Any help?

There's no real need to split this functionality over multiple functions.
All you need to do is create the new note and append it to the DOM, instead of recreating all the HTML every time.
function AddNote (){
var input = document.getElementById("txt").value;
var date = d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();
var time = d.getHours() + ":" + d.getMinutes();
var n = new NoteCrt(input,time,date);
notes.push(n);
// store
notes_j = JSON.stringify(notes, null, " ");
localStorage.setItem("NOTE",notes_j);
notes_p = JSON.parse(notes_j);
console.log(notes_p);
// show
for (var i = 0 ; i < notes.length ; i++) {
var new_note = document.createElement("span");
new_note.id="fade"; new_note.class="note_input";
new_note.innerHTML += "<div class='flow' ><p>"+notes[i].input+"</p></div></br>" + "</br>" +"Time: "+ notes[i].time + "</br>" +"Date: "+ notes[i].date;
}
document.getElementById("note_div").appendChild(new_note);
}

function AddNote (){
var input = document.getElementById("txt").value;
var date = d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();
var time = d.getHours() + ":" + d.getMinutes();
var n = new NoteCrt(input, time, date);
var notes = JSON.parse(localStorage.getItem("NOTE")) || [];
notes.push(n);
console.log(notes);
localStorage.setItem("NOTE", JSON.stringify(notes, null, " "));
var node_div = document.getElementById("note_div");
var el = document.createElement('span');
el.id = "fade";
el.classList.add('note_input');
el.innerHTML =
"<div class='flow'>" +
"<p>" + n.input + "</p>" +
"</div>" +
"</br>" +
"</br>" +
"Time: " + n.time +
"</br>" +
"Date: " + n.date;
node_div.appendChild(el);
}
You should note that it appears that you are assigning the id fade to multiple spans. If that is the case, you should consider making it a class.

Related

I wan to print my text into the <div> tag, but it doesn't print

This is my Ajax Function
function xhttp() {
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
var hourArray;
// Define a callback function
xhttp.onload = function () {
var parser, xmlDoc;
var text = this.responseText;
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
hourArray = xmlDoc.getElementsByTagName("item");
booking_hours(hourArray);
};
// Send a request
xhttp.open("GET", "test.xml");
xhttp.send();
}
When any is clicked ajax function will work
dataCel.on("click", function () {
var thisEl = $(this);
var thisDay = $(this).attr("data-day").slice(8);
var thisMonth = $(this).attr("data-day").slice(5, 7);
$(".c-aside__num").text(thisDay);
$(".c-aside__month").text(monthText[thisMonth - 1]);
$(".c-aside__year").text(dateObj.getUTCFullYear() + indexYear);
xhttp();
dataCel.removeClass("isSelected");
thisEl.addClass("isSelected");
});
When ajax will work I want to read hours to my text and print this text into div tag
function booking_hours(hourArray) {
var table;
for (var i = 0; i < hourArray.length; i++) {
if (parseInt(hourArray[i].childNodes[0].nodeValue) < 9)
table +=
"<div data-hours='0" +
hourArray[i].childNodes[0].nodeValue +
".00-0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
"0" +
hourArray[i].childNodes[0].nodeValue +
".00 - 0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
else if (parseInt(hourArray[i].childNodes[0].nodeValue) == 9) {
table +=
"<div data-hours='0" +
hourArray[i].childNodes[0].nodeValue +
".00-0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
"0" +
hourArray[i].childNodes[0].nodeValue +
".00 - " +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
} else {
table +=
"<div data-hours='" +
hourArray[i].childNodes[0].nodeValue +
".00-" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
hourArray[i].childNodes[0].nodeValue +
".00 - " +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
}
}
console.log(table.slice(9));
document.getElementsById("hoursList").innerHTML = table.slice(9);
}
This console log print this console.log(table.slice(9));
<div data-hours='02.00-03.00' class='hour_cell'><p>02.00 - 03.00</p></div><div data-hours='08.00-09.00' class='hour_cell'><p>08.00 - 09.00</p></div><div data-hours='10.00-11.00' class='hour_cell'><p>10.00 - 11.00</p></div><div data-hours='16.00-17.00' class='hour_cell'><p>16.00 - 17.00</p></div>
But this innerHTML doesn't print what console log printed
document.getElementsById("hoursList").innerHTML = table.slice(9);
Div tag that I want to use.
<div id="hoursList" class="hours__list"></div>

Append Image and text together to the list in javascript

I am doing a simple weather application. As you can see from the code below, I am showing 5-day forecast, I want to show as a list, but there is a problem that I can not append an image to my list elements for every day.
my js file
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var t = document.createTextNode("Date: " + forecast[i].date.toString().substring(8, 10)
+ "/" + forecast[i].date.toString().substring(5, 7) + " "
+ "Current Temperature: " + forecast[i].temperature.toString() + " "
+ "Maximum: " + forecast[i].temperature_max.toString() + " "
+ "Minimum: " + forecast[i].temperature_min.toString() + " "
+ "Description: " + forecast[i].text.toString() + " ");
li.appendChild(t);
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = "";
my Html file
<div id="myDIV" class="header">
<h2 style="margin:5px">Weather Application</h2>
<p id="title">You can search here.</p>
<input type="text" id="myInput" placeholder="Search...">
<span onclick="gettingJSON()" class="addBtn">Add</span>
</div>
<ul id="myUL">
</ul>
My List output like this.
My Question about; For example, I want to add images next to the "light rain" and other 5 days as you can see below picture. How can I add it?
Here is what you're missing:
var image = document.createElement("img");
image.setAttribute("src", iconurl);
li.appendChild(image);
If you want the image before the text, you should append it first.
You need to create an image element, set its src to the url, and append it to your li.
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var img = li.appendChild(document.createElement('img'));
img.src = iconurl;
var t = // ...
You simply didn't used this variable at all iconurl
You can create Image element as
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var t = document.createTextNode("Date: " + forecast[i].date.toString().substring(8, 10) + "/" + forecast[i].date.toString().substring(5, 7) + " " + "Current Temperature: " + forecast[i].temperature.toString() + " " + "Maximum: " + forecast[i].temperature_max.toString() + " " + "Minimum: " + forecast[i].temperature_min.toString() + " " + "Description: " + forecast[i].text.toString() + " ");
var img = document.createElement("img");
img.src=iconurl;
img.width=20;
img.height=20;
li.appendChild(t);
li.appendChild(img); document.getElementById("myUL").appendChild(li); document.getElementById("myInput").value = "";

How to use a js function inside $.getJSON?

how can I use my function JSONtoDate inside $.getJSON? This doesn´t work... val.timePosted return a string like 1448038589396, this work fine without the function but when I trying use the function to convert the str to date everything disappear
$(document).ready(function() {
function JSONtoDate(num){
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return(date);
}
  $.getJSON("http://www.freecodecamp.com/news/hot", function(json) {
var html = "";
var count = 0;
json.map(function(val) {
if(count == 0){
html += "<div class = 'row' >";
}
html += "<div class = 'stories col-md-3'>";
html += "<a href = " + val.link + " > <img src = " + val.image + " width = ' 200px'>";
html += "<p>" + val.headline + "</p> </a>";
html += "<p>" + val.rank + "</p>";
html += "<p>" + JSONtoDate(val.timePosted) + "</p>";
html += "</div>";
count += 1;
if(count == 4){
html += "</div>";
count = 0 ;
}
});
     $(".section").html(html);
});
});
Your function JSONtoDate expects a Date object as parameter, but you provide a String - "1448038589396". You can either pass a date, constructed from the Number value val.timePosted
html += "<p>" + JSONtoDate(new Date(parseInt(val.timePosted))) + "</p>";
^^^^^^^^^^^^^^^^^^ ^^
or let your function accept a string parameter:
function JSONtoDate (dateString) {
var date = new Date(parseInt(dateString));
var month = date.getMonth() + 1;
...
You have a JS error here:
1448038589396 is not a Date Object and it throws :
Uncaught TypeError: num.getMonth is not a function
try the following in jsFiddle
in JSONtoDate try the following
function JSONtoDate(num){
var num = new Date(num);
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}
http://jsfiddle.net/Lbt9jy8c/
I converted a string to UNIX timestamp based new Date() Object

array for loop, looping too many times javascript

Instead of looping through one time to show
id1
id2
id3
it loops through 3 times before stopping. what can i put to make it loop through only once.
html:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
javascript:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
//for loop to display results
var text="";
var i;
for (i = 0; i < IdArray.length; i++){
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
document.getElementById("show_me").innerHTML = text;
}
It iterates three times, because you loop for the length of the array, which has 3 items.
If you want to 'iterate' once, you can just omit the for loop:
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
But I think you actually wanted to do this:
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}
That way you use the loop what it's for: Iterate over an array of any length and repeat a piece of code for each item in the array.
Remove everything from the for loop, and add this instead:
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
Every thing is fine ... but please replaced the following code
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
with
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}

How can create toggleable divs using javascript's innerhtml function?

I am trying to import information from an XML file, and create a name which, when clicked, will show more information. This information will be inside a div with no display until the header has been clicked.
This is the idea. Doesn't work.
$(document).ready(function () {
$.ajax({
type: "Get",
dataType: "xml",
url: 'service.xml',
success: function (xml) {
$(xml).find('Service[Name="j1979"]').find("Define").each(function () {
var PID = $(this).attr("PID");
var name = $(this).find("Name").text();
var source = $(this).find("source").text();
var doffset = $(this).find("DOffset").text();
var type = $(this).find("Type").text();
var length = $(this).find("Lenght").text();
var scale = $(this).find("Scale").text();
var noffset = $(this).find("NOffset").text();
var units = $(this).find("Units").text();
var moreinfo = "<div id='moreinfo'>source += '\r\n' += doffset += '\r\n' += type += '\r\n' += length += '\r\n' += scale += '\r\n' += noffset += '\r\n' += units</div>";
document.getElementById("j1979").innerHTML += PID += " ";
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
document.getElementById("j1979").innerHTML += moreinfo;
});
}
});
});
Sorry for any obvious mistakes and/or ugly code.
I assume that this is what you want to achieve: DEMO
just assume that the script in the demo is inside the success function
first, you have some error in here
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
this will not add the p element to the element with id j1979 because you write it like that, where you should be writing it like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\" ></p>";
note the quotes at start and end, and the closing tag
second, there's no word or anything inside the p element that indicates that you could click it to show more information, so put the PID inside the p like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
here's the full code with some CSS style to hide it before the user click on the PID
$(document).ready(function () {
var PID = "testPID";
var name = "Random Name";
var source = "Google";
var doffset = "1000";
var type = "A-9001";
var length = "50CM";
var scale = "100";
var noffset = "0";
var units = "Some Units";
var moreinfo = "<div id='moreinfo'>source: " + source + "</br>" + "doffset: " + doffset + "</br>" + "type: " + type + "</br>" + "length: " + length + "</br>" + "scale: " + scale + "</br>" + "noffset: " + noffset + "</br>" + "units: " + units + "</div>";
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
});
#moreinfo {
display: none;
}
#j1979 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="j1979"></div>
From the code you have, you can use '+' operator to concatenate strings.
When you need to use single quote inside string defined with single quote, you can use backslash (\) as escape character before it.
Also, you need to hide the div with class "moreinfo" initially.
As for new line, if you want each attribute in new line in moreinfo class, it can be achieved by using HTML "pre" tag or "br" tag or some other way.
So code would be:
var moreinfo = "<pre id='moreinfo' style='display:none'> source = " + source + "\r\n doffset = " + doffset + "\r\n type = " + type + "\r\n length = " + length + "\r\n scale = " + scale + "\r\n noffset = " + noffset + "\r\n units = " + units +"</pre>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
or
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
If you want to toggle display on click, you can use ternary operator to give condition in onclick function:
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display == \'inline-block\' ? document.getElementById(\'moreinfo\').style.display = \'none\' : document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
I wrote a program where I needed to toggle a div with javascript. I found a solution with this code.
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
You can then call the function with:
toggle('.idOrClass');
make sure you use single quotes around the class or id name
Hope this helps! :)

Categories

Resources