Can someone explain to me how I do appending divs currently it just concats everything and it all looks like a mess. I want each trip to be inside separate divs
var origin = ' ';
var destination = ' ';
var distance = ' ';
var oneConcatedTrip = ' ';
var outerDiv = document.getElementById('demo');
var innerDiv = document.createElement('div');
var i = 1;
var query = firebase.database().ref('users/' + uid +'/waypoints/Work/2016/06').orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
origin = childSnapshot.val().origin;
destination = childSnapshot.val().destination;
distance = childSnapshot.val().distance;
innerDiv.className = 'block-' + i++;
outerDiv.appendChild(innerDiv);
oneConcatedTrip = origin + ' ' + destination + ' ' + distance;
innerDiv.innerHTML += oneConcatedTrip;
});
outerDiv.textContent = innerDiv.innerHTML;
});
You are reusing the same reference of innerDiv. You need to create different new div for every trip.
Move : var innerDiv = document.createElement('div'); into the for loop.
Check example below :
Your code :
Note the innerDiv has a blue border and its only one box that you can see.
var outerDiv = document.getElementById('demo');
var innerDiv = document.createElement('div');
for (var i = 1; i < 5; i++) {
innerDiv.className = 'block';
outerDiv.appendChild(innerDiv);
var oneConcatedTrip = 'origin destination distance';
innerDiv.innerHTML += oneConcatedTrip;
}
.block {
border: 2px blue solid;
}
<div id="demo">
</div>
Correct Way
Now that for every iteration there is a new div, note that there are different boxes and not just one.
var outerDiv = document.getElementById('demo');
for (var i = 1; i < 5; i++) {
var innerDiv = document.createElement('div');
innerDiv.className = 'block';
outerDiv.appendChild(innerDiv);
var oneConcatedTrip = 'origin destination distance';
innerDiv.innerHTML += oneConcatedTrip;
}
.block {
border: 2px blue solid;
}
<div id="demo">
</div>
Related
I am trying to change the css property of the "node"-class by clicking on the div inside of it which got the class "expand".
When I click on the "expand" div inside the "note", I want to go to parent "note" for changing it size:
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function () {
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue +
"<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for (var i = 0; i < expand.length; i++) {
expand[i].addEventListener("click", function () {
notes[i].style.size = "3000px";
})
}
})
You have to re-get the values of expand and notes, because after you add them to your html, the two variables expand and notes, dont know yet that you have added them and they don't contain them. ( you also have to removee the eventlistner otherwise you're gonna get a bugg at approximately twelve notes added :D because you will have too many eventListners on each element
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function(){
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue + "<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for( var i = 0; i < expand.length; i++){
const note = notes[i];
expand[i].addEventListener("click", function() {
note.style.size = "3000px";
note.style.backgroundColor = "red";
});
}
})
#notespace {
width: 100%,
height: 100%,
background: grey,
}
<button type="button" id="add">add</button>
<input id="text"/>
<div id="notespace">
</div>
You can use the parentNode attribute :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.parentNode.style.size = "3000px";
})
}
Or the closest() method :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.closest(".note").style.size = "3000px";
})
}
Note that closest() is not supported on IE.
I'm struggling to make this idea of mine work..
The idea is to auto-scroll the dynamically filled unsorted list.
This is how I've build the Unsorted List with List Items in JavaScript
$.getJSON(sportlink_url + 'programma?gebruiklokaleteamgegevens=NEE&aantaldagen=' + programma_dagen + '&eigenwedstrijden=JA&thuis=JA&uit=JA&' + sportlink_clientID, function (uitslag) {
for (let i = 0; i < Object.keys(uitslag).length; i++) {
//for (let i = 0; i < 1; i++) {
var aanvangstijd = uitslag[i].aanvangstijd;
var thuisteam = uitslag[i].thuisteam;
var uitteam = uitslag[i].uitteam;
var accommodatie = uitslag[i].accommodatie;
var competitiesoort = uitslag[i].competitiesoort;
var datumNumber = uitslag[i].datum.substring(0,2);
var datumMonth = uitslag[i].datum.slice(-4);
var datumMonthClean = datumMonth.substring(0,3);
//Fetch the DIV
var el = document.getElementById("match_program");
//Create new list item
var node = document.createElement("li");
node.setAttribute('role', 'presentation');
//Create ticketDiv
var ticketDiv = document.createElement("div");
ticketDiv.setAttribute('class', 'tg-ticket');
//Create timeBox
var timeBox = document.createElement("time");
timeBox.setAttribute('class', 'tg-matchdate');
timeBox.innerHTML = (datumNumber + " <span>" + datumMonthClean + "</span>");
//Create matchdetail
var matchDetail = document.createElement("div");
matchDetail.setAttribute('class', 'tg-matchdetail');
matchDetail.innerHTML = ("<h4>" + thuisteam + "<span> - </span>" + uitteam + " | " + aanvangstijd + ", " + accommodatie);
//Create themeTag
var themeTag = document.createElement("span");
themeTag.setAttribute('class', 'tg-theme-tag');
themeTag.innerHTML = (competitiesoort);
//Build the hole thing
ticketDiv.appendChild(timeBox);
matchDetail.appendChild(themeTag);
ticketDiv.appendChild(matchDetail)
node.appendChild(ticketDiv);
el.appendChild(node);
This is the Unsorted List in HTML
<ul id="match_program" class="tg-tickets tg-tabnav" role="tablist" data-autoscroll="">
</ul>
This is the function i'm currently using for auto-scroll, but it has .ulContent').height() > $('.ulContainer').height() and because my ulContent doesn't have a prefix height in CSS it's not going to work..
And I can't put a height prefix in CSS for the ulContent cause I don't know on forehand if it's going to be 500px of 800px, the unsorted list is being filled from a JSON string.
$(document).ready(function() {
if($('.ulContent').height() > $('.ulContainer').height()) {
setInterval(function () {
start();
}, 3000);
}
});
function animateContent(direction) {
var animationOffset = $('.ulContainer').height() - $('.ulContent').height();
if(direction == 'up') {
animationOffset = 0;
}
}
The animatie function is being called at the bottom of the HTML file just before the closing tags of the body
I manged to figure it out;
var amountGames = Object.keys(uitslag).length
var calulContent = amountGames * 116 + 500;
var setulContent = calulContent + "px";
document.getElementById('ulContent').style.height= setulContent;
That way the ulContent is always filled and the container uses a fixed number of 500px;
I would like to open a new page when I tap a cell (TR) in Javascript. I've searched a lot of tutorials online but it doesn't work as well. I hope that someone could help me. Thanks.
Here is my code:
function generateTableBirre()
{
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
cell.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
If you would like to show the table, here is the image:
In the Javascript below the table is created with 2 cells per row. In the first cell you'll find a div with a text paragraph. In the second cell you'll find a div with anchor and image.
Important: an id must be unique so I had to remove lines where duplicate id's were created. If you want to use extra selectors then you can use classList.add("...")
In the css you can style the image width, font, color, etc. For example #dvTable img { max-width: 250px; height: auto; border: 0; }
function generateTableBirre() {
// array containing records
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
// create table
var table = document.createElement('table');
table.classList.add("Birre");
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '20');
// loop through the array and create rows
for (var i = 0; i < birre.length; i++) {
var row = document.createElement('tr');
// loop from 0 to 1 to create two cells on each row
for (var j = 0; j < 2; j++) {
var cell = document.createElement('td');
// give each cell a inner div
var div = document.createElement("div");
div.classList.add("General-Div");
cell.appendChild(div);
// different content in cell 0 and cell 1
if (j == 0) {
// cell 0 contains paragraph
var par = document.createElement("p");
par.innerHTML = birre[i] + ' - ' + price[i];
div.appendChild(par);
} else {
// cell 1 contains image in an anchor
var anch = document.createElement('a');
anch.setAttribute('href', 'Antipasti.html');
div.appendChild(anch);
var img = document.createElement("img");
img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
anch.appendChild(img);
}
row.appendChild(cell);
}
table.appendChild(row);
}
// append table in id=dvTable
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableBirre();
<div id="dvTable">
</div>
try this,
function generateTableBirre() {
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
//var row = table.insertRow(-1);
//var cell = row.insertCell(-1);
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
row.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
So I have this HTML Code/Javascript,
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell');
spellSelect.setAttribute('name', 'spell');
spellLabel.setAttribute('for', 'spell');
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 1;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
And am trying to retrieve the .value of the <select id="spell"> options. However, the console returns an undefined, instead of vanish or teleport.
Can anyone point me in the right direction for this?
Well:
Id should be unique so I added spellSelect.setAttribute('id', 'spell' + spellNumber); ( + other rows)
Also multipleSpell = $("#spell" + spellCheck).val();
And console.log(multipleSpell); is called only once at the begining -> you should change it to function too
`
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell' + spellNumber);
spellSelect.setAttribute('name', 'spell' + spellNumber);
spellLabel.setAttribute('for', 'spell' + spellNumber);
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 0;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell" + spellCheck).val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
More info here.
Edited:
Well, i see you are trying to get all select values. Why not try this?
function generateYaml() {
var spellCheck = 1;
var selects = $("select").each(function (index, element) {
var value = $(element).val()
console.log("The value at index %d is %s", index, value);
spellCheck++
});
}
This way you iterate over all the selects, and get their values inside the loop. Try it here (open the developer console):https://darkcyanpointlessbooleanvalue--parzibyte.repl.co/
so what I want to do is get a random word, and put each individual characters of it in an array to then create divs like
for(i = 0; i <= wlength; i++ ){
var div = document.createElement('div');
div.id = 'aa';
document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = "- " + i;
div.style.left = '32px';
}
and instead of div.innerHTML = "- " + i;
It would create a div for each individual characters of a word.
How can I do that? Thanks in Advance!!
function listChars(word){
var wLength = word.length, div;
for(var i = 0; i < wLength; i++ ){
div = document.createElement('div');
div.id = 'aa';
div.appendChild(document.createTextNode('- ' + word[i]));
div.style.left = '32px';
document.body.appendChild(div);
}
}
var word = 'cat';
listChars(word);
Just for completeness:
let myWord = 'hello'
myWord.split('')
.map((c, i) => {
let div = document.createElement('div')
div.id = 'aa' + i
div.innerHTML = c
div.style.left = '32px'
return div
})
.forEach(div => document.body.appendChild(div))
Is this what you're looking for?
let word = 'randomword'
let char = []
for (let i = 0; i < word.length; i++) {
char.push(word[i])
const div = document.createElement('div')
div.id = char[i]
document.body.appendChild(div)
}
let word = 'randomword'
let char = []
for (let i = 0; i < word.length; i++) {
char.push(word[i])
const div = document.createElement('div')
div.id = char[i]
div.innerHTML = char[i]
/*
or if you need elements that you can manipulate...
...
const ele = document.createElement('text')
const txt = document.createTextNode(char[i])
ele.appendChild(txt)
div.appendChild(ele)
*/
document.body.appendChild(div)
}
div {
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
}
div:nth-child(even) {
background: grey;
}
div:nth-child(odd) {
background: orange;
}
And here is the codepen that you can play around with.
You could iterate the word and take for every letter a new div.
var i, // declare all variables on top
word = 'Weltschmerz', // choose a right word
wlength = word.length,
div;
for (i = 0; i < wlength; i++) {
div = document.createElement('div'); // create a new element
div.id = 'aa' + i; // build a unique id for later access
div.innerHTML = word[i]; // take the letter as content
div.style.left = '32px'; // does not work here, because of relative pos
div.style.display = 'inline'; // style some things
div.style.border = '1px green solid';
div.style.padding = '2px';
div.style.margin = '1px';
document.body.appendChild(div); // append actual div to body
}
document.getElementById('aa0').style.borderColor = 'red';
You may want to map the words characters to an HTML string containing the divs, which you can assign to the dom easily:
var word = "Strebsamkeit";
document.body.innerHTML = Array.from(word).map( char =>
`<div id='aa'>
${char}
</div>`
).join("");
Might be easier to replace each character with the div HTML:
var word = "cat"
var html = word.replace(/(.)/g, '<div id="aa$1" style="left: 32px;">- $1</div>\n')
document.body.innerHTML = html
console.log(html)