Template literals are not interpolating variables - javascript

Just noticed today that template literals with html tags don't work, or maybe I wrote it wrong?
I tried to include p tags in the template literals (which I commented out in the snippet), but it didn't work. Does anyone have any ideas? Thanks!
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
//content += '`<p>${i.name} is a ${i.species}.</p>`'; <--this one doesn't work
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>

Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.
You need to change this:
'`<p>${i.name} is a ${i.species}.</p>`'
to this:
`<p>${i.name} is a ${i.species}.</p>`
The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.
See the following working example:
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
// content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
content += `<p>${i.name} is a ${i.species}.</p>`;
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Read more about template literals in the documentation.

Related

Javascript how to change page title with user input

The thing i wanna do is when user writes something to input and sumbits it, the page will change to the input.
Example:
If user writes "Web" to the input, the page title should change to "Web"
Here's the code:
JS:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").textContent;
document.getElementById("title").innerHTML = newTitle;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title">Web Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center><label id="originLabel">Welcome to Web Editor!</label><br></center>
<br><label id="changeTitleLabel">Change the title of Web: </label><br>
<input type="text" id="newTitle"><br>
<button type="button" id="titleSumbitBtn">Change</button>
</body>
</html>
You can assign new title to the document like this:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
This is actual implementation but keep in mind that it must run after the DOM element with id newTitle.
If you put your <script> tag inside <head>, you'll need DOMContentLoaded:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
})
try this:
document.getElementById("titleSumbitBtn").addEventListener("click", function (){
var newTitle = document.getElementById("newTitle").value;
document.getElementById("title").innerText = newTitle;
})

on pressing the cancel button of a todo list item, it removes all the below to-do list items, here is the code of my to-do list

Here is my HTML and JS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script src="functions.js"></script>
</body>
</html>
Here is my Javascript code
'use strict'
const buttonclick = document.getElementById('button')
const list = document.getElementById('lists')
const a = "<span><button class = 'rbutton'>X</button></span>" //list-item button
const clickhandler = () => {
const text = document.getElementById('text')
//creating a list element
if(text.value != ''){
let Newdiv = document.createElement('div')
// appending elements
Newdiv.innerHTML = text.value + a
list.appendChild(Newdiv)
let b = document.getElementsByClassName('rbutton')
if(b !=[]){
for(let i = 0; i < b.length; i++){
b[i].addEventListener('click', function(){
b[i].parentElement.parentElement.remove();
console.log(b)
})
}
}
//reseting the textarea value
text.value = ''
}
}
buttonclick.addEventListener('click', clickhandler)
An error in shown on delete a item: Cannot read property 'parentElement' of undefined at HTMLButtonElement. .
Can someone please explain what is wrong in my code and what does the error mean.
thankyou
On every click of the button you are attaching event handlers to the whole group again.
On the first iteration, 1st button has one delete handler.
On second iteration, 1st button has 2 event handler(one for buttons[0] and one for buttons[1]), and 2nd has one.
So on.
Use this. It will always point to the element to the event on which the event handler is attached:
this.parentElement.parentElement.remove();
Another way is to simply use this.parentElement.parentElement.remove()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script>
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
this.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
</script>
</body>
</html>
You should use window.event.target.parentElement... to get the button instead of b[i].parentElement....
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
window.event.target.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
</body>
</html>

How to create a bootstrap list group with two arrays?

I'm currently creating a dashboard and I want to create a "Bootstrap List Group" which should show a list of friends of the current dashboard.
I have given to arrays like this:
friendsID[id1, id2, id3]
friendsName[name1, name2, name3]
I want to create a method in javascript so that the result looks like this.
<div class="list-group">
name1
name2
name3
</div>
Would love to here how you would manage this because I am a little bit desperate and have no clue how to do this.
Here You can use document.write() to solve the problem it is used when the path for the html is not needed
var friendsID = ['id1','id2','id3'];
var i=0;
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
document.write("<a href='/dashboard/"+friendsID[i]+"' class='list-group-item list-group-item-action'>"+friendName[i]+"</a><br>")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./java.js"></script>
</body>
</html>
Or You can Use Innerhtml in this the path inside which div the html must be kept is determined by the programmer.
var friendsID = ['id1','id2','id3'];
var i=0;
var statement =[0,0,0];
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
statement[i]="<a href='google.com/"+friendsID[i]+"'>"+friendName[i]+"</a><br>";
console.log(statement[i]);
document.getElementById("hello").innerHTML+=statement[i];
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="hello"></div>
<script src="./java.js"></script>
</body>
</html>
You can do something like this
const friendsID = ["id1", "id2", "id3"]
const friendsName = ["name1", "name2", "name3"]
let i = 0;
for (i = 0; i < friendsID.length; i++) {
let list = '' + friendsName[i] + ""
$(".list-group").append(list)
}
<div class="list-group">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
check this out
https://jsfiddle.net/cloud_zero/hacLpe3g/4/
var arry1 = ["name1", "name2", "name3"];
var arry2 = ["id1", "id2", "id3"];
// merging two array
var result = arry1.reduce(function(acc, cur, index) {
return Object.assign(acc, { [arry2[index]]: cur })
}, {})
// generating links
var text = Object.keys(result).map(function(key) {
return `${ result[key] }`;
});
// finally adding to dom
document.querySelector('.list-group').innerHTML = text.join('');
first i merged two array to object (result)
then i generate links from the result
lastly linked added to DOM
First of all thank you for your great solutions!
I also tried my best and came up with this here.
var friendsIDs = ["id1", "id2", "id3"];
var friendsNames = ["name1", "name2", "name3"];
var friendLinks = [];
for (i=0; i < friendsIDs.length; i++){
friendLinks.push("<a href=/dashboard/" + friendsIDs[i] + " class=\'list-group item list-group-item-action\' >" + friendsNames[i] + "</a>")
}
//Create HTML Element for the Company Relations
var linkTarget = document.getElementById('linkTarget');
for(i=0; i < friendLinks.length; i++){
linkTarget.innerHTML += friendLinks[i];
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="list-group" id="linkTarget"></div>

Why is document.getElementById() not working?

I want to make a program which adds a textbox every time you click a button. Here's my code:
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="linelist"></div><br />
<button id="addline" onclick="Addline();">+</button>
</body>
</html>
When I run it, it generates an error. Why is this occurring?
You have to define linelist outside the functions first with let or var:
let linelist = null;
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button
class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}

Iterate through all SVG elements in JS

I'm not able to go through all children of an SVG file in JavaScript. I want to go through all the paths and perform a function on them(changing them to polygons).
I've tried creating an array of paths using querySelectorAll("path");, but it didn't work. Now I'm trying to sift through all the elements in the SVG file, converting paths as I go.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>
This gives me two errors:
XML Parsing Error: syntax error
Location: file:///C:/Users/Temp/Desktop/Experiment.html
Line Number 1, Column 1:.
ReferenceError: $ is not defined.
I've stopped trying to use doc.children() since it wasn't working.
Just add the jQuery library into your project.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
CODE:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>

Categories

Resources