dynamic gradient value is not adding to the css - javascript

i am trying to change dynamically background-image liner gradient.i am getting the liner gradient value in console but its not changing the display! if I put the value manually in CSS it works but does not work dynamically!! what is wrong I am doing?
let inputFirst = document.getElementById("input1");
let inputSecond = document.getElementById("input2");
let buttons = document.querySelectorAll("label");
let display = document.querySelector(".container");
let color1;
let color2;
let gradientPosition = "";
inputFirst.addEventListener("input", () => {
color1 = inputFirst.value;
});
inputSecond.addEventListener("input", () => {
color2 = inputSecond.value;
});
buttons.forEach((button) => {
button.addEventListener("click", () => {
gradientPosition = button.id;
display.style.backgorundImage = `linear-gradient(${gradientPosition}, ${color1},
${color2})`;
console.log(`linear-gradient(${gradientPosition}, ${color1}, ${color2})`)
;
});
});
//linear-gradient( to right, #671313, #af1d1d)

Related

Javascript and Google Sheet - Display only one element of array

I'm learning javascript, hence my question might be a bit silly/simple.
Following a tutorial on Udemy, I was able to display a spreadsheet from Google Sheet in my website, using javascript to retrieve all rows contained in the document and pass them to a container in an HTML page.
This is great.
Now I would like to visualise only one row at a time, at a specific interval.
After some search I realised I can do this by using getElementById in conjunction with .innerHTML within a loop but I can't figure out what I am supposed to pass and where.
So, here is the HTML I'm using
<!DOCTYPE html>
<html><head><title>Testing Data from Sheets</title></head>
<body>
<div class="output"></div>
<script src="sheets.js"></script>
</body>
</html>
And here is the JS
const sheetID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const base = `https://docs.google.com/spreadsheets/d/${sheetID}/gviz/tq?`;
const sheetName = 'quotes';
let qu = 'Select D';
const query = encodeURIComponent(qu);
const url = `${base}&sheet=${sheetName}&tq=${query}`;
const data = [];
document.addEventListener('DOMContentLoaded', init);
const output = document.querySelector('.output');
function init() {
console.log('ready');
fetch(url)
.then(res => res.text())
.then(rep => {
//console.log(rep);
const jsData = JSON.parse(rep.substr(47).slice(0, -2));
console.log(jsData);
const colz = [];
jsData.table.cols.forEach((heading) => {
if (heading.label) {
colz.push(heading.label.toLowerCase().replace(/\s/g, ''));
}
})
jsData.table.rows.forEach((main) => {
//console.log(main);
const row = {};
colz.forEach((ele, ind) => {
//console.log(ele);
row[ele] = (main.c[ind] != null) ? main.c[ind].v : '';
})
data.push(row);
})
maker(data);
})
}
function maker(json) {
const div = document.createElement('div');
div.style.display = 'grid';
output.append(div);
let first = true;
json.forEach((el) => {
//console.log(ele);
const keys = Object.keys(el);
div.style.gridTemplateColumns = `repeat (${keys.length} ,'1fr')`;
if (first) {
first = false;
keys.forEach((heading) => {
const ele = document.createElement('div');
//ele.textContent = heading.toLocaleUpperCase();
ele.style.background = 'black';
ele.style.color = 'white';
ele.style.fontFamily = 'Helvetica';
div.append(ele);
})
}
keys.forEach((key) => {
const ele = document.createElement('div');
//ele.style.border = '1px solid #ddd';
ele.textContent = el[key];
ele.style.background = 'black';
ele.style.color = 'white';
ele.style.fontFamily = 'Helvetica';
div.append(ele);
})
console.log(keys);
})
}
Thanks heaps for helping!
I tried using the following from other messages I've found on the forum:
var i = 0; // the index of the current item to show
setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('output')
.innerHTML = jsData[i++];
if (i == jsData.length) i = 0;
}, 1000);

How to create a dynamic list, which removes deleted items from an array in JS?

I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.
For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin.
How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help.
Here is my code:
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
output.removeChild(paragraph)
})
})
You can find an element in the array by name and remove it from there:
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
output.removeChild(paragraph)
})
})
<input id="name">
<button id="button">button</button>
<div id="output">output</div>
Every time the event handler to delete an item is called, just collect all of the text of each item and convert it into an array.
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
/*
This removes an <li>, if you don't change your "paragraph" then
change 'li' to 'ul'
*/
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const item = document.createElement('li');
item.textContent = name+' ';
list.append(item);
const del = document.createElement('button');
del.textContent = "X";
item.append(del);
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});
<input id='user'><button class='add'>ADD</button>
<ul class='list'></ul>
Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const paragraph = document.createElement('div')
paragraph.style.display = 'flex'
const item = document.createElement('li');
item.textContent = name + ' ';
list.append(paragraph);
paragraph.append(item)
const del = document.createElement('button');
del.textContent = "X";
paragraph.append(del);
del.addEventListener('click', function() {
this.closest('div').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});

Javascript selector to effect the multiple elements

I've already created a recipe box and it works with Javascript queryselector which increases the portion number and decreases it.
The problem with queryselector is that it only effects on the first element with the specific class. So when I duplicated this element, nothing works on the second element.
// Recipe calculator plus/minus actions
const plusBtn = document.querySelector(".portion-plus");
const minusBtn = document.querySelector(".portion-minus");
const portionNumber = document.querySelector(".portion-number span.portion-counter");
// thenum = "foo3bar5".match(/\d+/)[0]
const portionWord = document.querySelector(".portion-number span.portion-word");
const contentAmount = document.querySelectorAll(".content-list li span.content-amount");
let initRecipeValue = [];
window.addEventListener("load", () => {
contentAmount.forEach(elem => {
initRecipeValue.push(elem.innerText);
});
});
let count = 1;
// Increasing the counter
if (plusBtn && minusBtn) {
plusBtn.addEventListener("click", () => recipeCalculation(0, 1));
minusBtn.addEventListener("click", () => recipeCalculation(1, -1));
}
const recipeCalculation = (limit, addSub) => {
if (count > limit) {
count += addSub;
//console.log(count);
portionNumber.textContent = count;
contentAmount.forEach((content, index) => {
content.textContent = initRecipeValue[index] * count;
});
portionWord.textContent = count > 1 ? "Portionen" : "Portion";
}
};

Changing content in multiple columns with a single button click

I am trying to change multiple columns with a single button click, after a click the image should change, the title and a phrase. I am only able to apply this to the first column. I tried iterating the columns with querySelectorAll() and searched answers in other forums.?
Also is it possible to assign a different random image to each column with the same single button click?
Thank you in advance!
const images = ['sandwich', 'cookie', 'monster', 'telegram', 'gym']
const inputName = document.getElementById('input-name');
const inputPhrase = document.getElementById('input-phrase');
const btnSubmit = document.querySelector('.input-btn');
const btnClr = document.querySelector('.clr-btn');
const row = document.querySelectorAll('.column');
const image = document.querySelector('.column img');
const title = document.querySelector('.name');
const phrase = document.querySelector('.phrase');
randomImage = Math.floor(Math.random() * images.length);
logoImage = images[randomImage];
window.addEventListener('DOMContentLoaded', function() {
// createLogo()
})
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
row.forEach(function(col) {
col.classList.add('change');
image.src = `./images/${logoImage}.png`;
title.textContent = inputName.value
phrase.textContent = inputPhrase.value
})
});
Instead of using a variable to refer to the image/name/phrase, you should reference them by col and queryselector in each iteration.
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
row.forEach(function(col) {
randomImage = Math.floor(Math.random() * images.length);
col.classList.add('change');
col.querySelector("img").src = './images/' + images[randomImage] + '.png';
col.querySelector(".name").textContent = inputName.value
col.querySelector(".phrase").textContent = inputPhrase.value
})
});

onclick toggle between various text

I want to toggle between multiple text when i click button.I have created a solution but i would to see a better solution and at end of last click event function i want it to continue to start from beginning.
var qarray = ['canada', 'india', 'america']
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
var one = textselect.textContent = qarray[0];
btn.addEventListener('click', function quoteone() {
var two = textselect.textContent = qarray[1];
btn.addEventListener('click', function() {
var three = textselect.textContent = qarray[2];
})
})
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>
When you define a new event listener, you're not removing the old one. So eventually all the listeners run, and they keep adding more each time you click.
Just use a single event listener that uses a global variable to hold the current array index.
var qarray = ['canada', 'india', 'america'];
var qindex = 0;
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
textselect.textContent = qarray[qindex];
qindex = (qindex + 1) % qarray.length;
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>
The modulus operator is used to make the index wrap around to 0 when you reach the end of the array.
var qarray = ['canada', 'india', 'america']
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
var countClick =0;
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
if(qarray.length > countClick) {
textselect.textContent = qarray[countClick];
countClick++;
} else {
countClick =0;
textselect.textContent = qarray[countClick];
}
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>

Categories

Resources