How to show and hide nested DIVs using javascript - javascript

I have two divs like following:
<div id="soil-trigger"
onclick="getWidgetData('soil-trigger'); getWidgetSoilChart();"></div>
<div id="water-trigger"
onclick="getWidgetData('water-trigger'); getWidgetWaterChart();"></div>
Clicking on one div (i.e: soil-trigger/water-trigger) generates a chart under time-series panel. For doing this I am using follwoing JS:
function getWidgetData(name){
var curEl = document.getElementById('time-series');
curEl.className = "active";
var el7 = document.getElementById('system-series');
var el8 = document.getElementById('cluster-series');
var curE2 = document.getElementById('system-health');
var curE3 = document.getElementById('cluster-info');
curE2.className = "";
curE3.className = "";
el7.className = "hide";
el8.className = "hide";
widgetEl = document.getElementById("soil-chart");
widgetEl5 = document.getElementById("water-chart");
var el = document.getElementById('soil-chart');
el.className = "";
var el5 = document.getElementById('water-chart');
el5.className = "";
if(name == 'soil-trigger'){
widgetEl.innerHTML = document.getElementById('soil-chart').outerHTML;
el.className = "show";
el5.className = "hide";
}
if(name == 'water-trigger') {
widgetEl5.innerHTML = document.getElementById('water-chart').outerHTML;
el5.className = "show";
el.className = "hide";
}
}
My code that I provided here is working like this:
When I click on soil-trigger it is showing chart under time-series for soil-data, but not showing anything under system-series and cluster-series.
Again, when I click on water-trigger it is showing chart under time-series for water-data, but not showing anything under system-series and cluster-series.
What I actually need when I will click on soil-trigger it will show three different charts under time-series, system-series, and cluster-series for soil data. Again when I will click on water-trigger it will show three different charts under time-series, system-series, and cluster-series for water data.
How can I achieve that by changing my code. Any help please.
Thanks

function getWidgetData(name) {
var timeSeries = document.getElementById('time-series'),
systemSeries = document.getElementById('system-series'),
clusterSeries = document.getElementById('cluster-series'),
systemHealth = document.getElementById('system-health'),
clusterInfo = document.getElementById('cluster-info'),
waterChart = document.getElementById("water-chart"),
soilChart = document.getElementById('soil-chart');
timeSeries.className = "active";
systemHealth.className = "";
clusterInfo.className = "";
systemSeries.className = "hide";
clusterSeries.className = "hide";
soilChart.className = "";
waterChart.className = "";
if (name == 'soil-trigger') {
soilChart.innerHTML =soilChart.outerHTML;
soilChart.className = "show";
waterChart.className = "hide";
}
if (name == 'water-trigger') {
waterChart.innerHTML = waterChart.outerHTML;
waterChart.className = "show";
soilChart.className = "hide";
}
}
Your code can be broken down like this, its a quick re-factoring and prone to errors. May be you can debug this yourself now.
soilChart.innerHTML =soilChart.outerHTML;//??????????

Related

How to randomize a position for my input with JS?

I'm doing a little game that is about a questions-answers game, that has 3 options and only one is the right one. So, what I'm trying to do is, every time I open the page, I randomize the correct answer, so, the player can't just memorize the positions, he will be obligate to remember the true answer. I already know how to randomize the right button, doing it with a random number and stuff like that, but, with this problem, just randomize the right button isn't what I need, cuz I have to change the position of the answer too. So, this is my code.
const vintecinco = document.getElementById('312');
const vinteseis = document.getElementById('314');
const vintesete = document.getElementById('214');
vinteseis.addEventListener('click', acerto);
function acerto() {
var msg = document.createElement('p');
msg.textContent = 'Voce acertou!';
msg.style.cssText = 'color: green;'
document.body.appendChild(msg);
var prosseguir = document.createElement('a');
prosseguir.textContent = 'Próxima pergunta!'
prosseguir.href = 'q3.html';
document.body.appendChild(prosseguir);
vintecinco.disabled = true;
vinteseis.disabled = true;
vintesete.disabled = true;
}
vintecinco.addEventListener('click', erro);
vintesete.addEventListener('click', erro);
function erro() {
var msgerro = document.createElement('p');
msgerro.textContent = "Voce errou!";
msgerro.style.cssText = 'color: red;';
document.body.appendChild(msgerro);
var voltar = document.createElement('a');
voltar.textContent = 'Recomeçar!'
voltar.href = 'index.html';
document.body.appendChild(voltar);
vintecinco.disabled = true;
vinteseis.disabled = true;
vintesete.disabled = true;
}
<main>
<p>Qual o número de pi?</p>
<input type="submit" value="3,12..." id='312'>
<input type="submit" value="2,14..." id='214'>
<input type="submit" value="3,14..." id='314'>
</main>
What kind of thing I could do to get random positions without compromise my right answer?
Now I did some changes and I created a test file. I'm trying to do something like that, but now, I can't change the value of the 2 wrong answers, they're default. How could I change it?
var random = Math.floor(Math.random() * 3);
for(var i=1;i<=10;i++) {
console.log(i);
var button = document.getElementById('btn' + i);
if(random == i) {
button.addEventListener('click', prize);
button.value = '1';
}
else {
button.addEventListener('click', closewindow);
button.value = '2';
}
}
There are many ways to do what you want, depending on the rest of the application, one or the other may be better for you, an example:
var input = [];
function acerto() {
var msg = document.createElement('p');
msg.textContent = 'Voce acertou!';
msg.style.cssText = 'color: green;'
document.body.appendChild(msg);
var prosseguir = document.createElement('a');
prosseguir.textContent = 'Próxima pergunta!'
prosseguir.href = 'q3.html';
document.body.appendChild(prosseguir);
input.forEach((i)=>{
i.disabled = true;
});
input = [];
}
function erro() {
var msgerro = document.createElement('p');
msgerro.textContent = "Voce errou!";
msgerro.style.cssText = 'color: red;';
document.body.appendChild(msgerro);
var voltar = document.createElement('a');
voltar.textContent = 'Recomeçar!'
voltar.href = 'index.html';
document.body.appendChild(voltar);
input.forEach((i)=>{
i.disabled = true;
});
input = [];
}
// question, true, false, false...
var res = ["Qual o número de pi?", "3.14", "2.14", "3.12"];
var quest = document.getElementsByTagName("main")[0];
// Create Question
quest.innerHTML = "<p>" + res.splice(0, 1)[0] + "</p>";
// Create Random input
for(i in res){
let temp = document.createElement('input');
temp.type = "submit";
temp.value = res[i];
if(i == 0){
temp.addEventListener('click', acerto);
}else{
temp.addEventListener('click', erro);
}
let rand = Math.floor((input.length+1) * Math.random());
input.splice(rand, 0, temp);
}
// Show input
input.forEach((i)=>{
quest.appendChild(i);
});
<main>
</main>

Is there a way to store whatever i append to DOM with js,in local storage in order to retrieve it after page reloads?

Ok,for testing purposes lets say i have a function where it appends <li> elements inside an <ol>
container,and i want to keep all list items i've added,is there a way to store them in Local Storage (or any other way,locally) so i can retrieve them every time i reload the page ?
I've studied a little bit in Window.localStorage api,i did'nt find a method to store a dynamic element like that,but again if there is something i would'nt know to recognize the right practice to do it,since i'm still a student.Any ideas?
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored =document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color="red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored =document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
div.appendChild(inputstobestored);
inputcounter++;
}
#div{
width:600px;
}
<html>
<body>
<ol id="div">
<button onclick="addText()" style="height:100px;width:100px">ADD TEXT</button>
<button onclick="addInputs()" style="height:100px;width:100px">ADD INPUTS</button>
</ol>
</body>
</html>
Here is a working fiddle: https://jsfiddle.net/3ez4pq2d/
This function calls saveInput to save the data to localstorage. Then it also generates the
inputs that are saved via loadInput.
This just stores the ID, COLOR and WIDTH. But using this as a base you can save additional fields also.
function saveinput(obj) {
saved = localStorage.getItem("items") || "[]"
saved = JSON.parse(saved)
saved.push(obj)
localStorage.setItem("items", JSON.stringify(saved))
}
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored = document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color = "red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
saveinput({
id: "input" + inputcounter,
color: "blue",
width: "600px"
})
div.appendChild(inputstobestored);
inputcounter++;
}
function loadInput() {
inputs = localStorage.getItem("items") || "[]"
inputs = JSON.parse(inputs)
inputs.forEach(function(input) {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = input.id;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = input.color;
inputstobestored.style.width = input.width;
div.appendChild(inputstobestored);
inputcounter++;
})
}
loadInput();

JavaScript: No toggle by click on <a> link

This is my code:
var works = document.querySelector('#works');
var cross_one = document.querySelector('#cross_one');
var works_navigation = document.querySelector('#works_navigation');
works.addEventListener('click', function (event) {
if (cross_one.style.display == "") {
cross_one.style.display = "none";
works_navigation.style.display = "block";
} else {
cross_one.style.display = "";
works_navigation.style.display = "none";
}
}
);
Included is a toggle function which works very well. But additionally, I need a command like this:
If a <a> link inside the construction gets clicked, it should not toggle.
My idea would be something like this:
var allLinks = document.links;
allLinks[i].onclick = function () {
cross_one.style.display = "none"; };
But I don't know who to indclude it.
Not sure i understood your question, but you might be looking for something like this :
In your HTML, add your link like
My Link
and in your JS
var toggle = true;
function doNotToggle() {
toggle = false;
}
var works = document.querySelector('#works');
var cross_one = document.querySelector('#cross_one');
var works_navigation = document.querySelector('#works_navigation');
works.addEventListener('click', function (event) {
if (toggle) {
if (cross_one.style.display == "") {
cross_one.style.display = "none";
works_navigation.style.display = "block";
} else {
cross_one.style.display = "";
works_navigation.style.display = "none";
}
}
});
and clicking your link will stop your eventListener function from doing anything.

array problems in JavaScript

I have built out an example of what I'm trying to accomplish. I want to be able to make an array of passwords where if one is correct, then they are all sent to another page. However, in the following example it is not working. If I input the name that is suppose to pop up with a hello message it states its wrong when I have it in an Array.
let textarea = document.getElementById('banner');
let okbutton = document.getElementById('btn');
let form = document.getElementById('user-form');
let textBox = document.getElementById('text-box');
let spanMe = document.getElementById('spans');
let userNameIs = ['marquise', 'quise', 'tom'];
textarea.style.display = 'none';
spanMe.style.display = 'none';
textarea.style.display = 'none';
okbutton.addEventListener('click', function() {
if (textBox.value.length <= 4) {
spanMe.style.display = 'block';
spanMe.style.color = 'red';
} else if (textBox == userNameIs[1]) {
spanMe.style.display = 'none';
textarea.style.display = "block"
textarea.innerText = 'hello' + ' ' + textBox.value;
} else if (textBox != userNameIs[1])
spanMe.style.display = 'block';
spanMe.style.color = 'red';
});

Javascript problems with dropdown return

I have multiple dropdowns on my site and I am trying to alter the code so that when the chosen product is clicked again, the dropdown resets (i.e. exits the dropdown). See here in the middle of the page: https://www.arieliandcompany.com/make-a-career-transition.html
I am not managing to find a solution that retains the functionality of changing between products on dropdown, or being able to enter the dropdown again after exiting.
I tried adding this line, which closed the dropdown, but it messed up other elements of the dropdown functionality as mentioned above:
chosenProd.onclick = function(){showIndProd(0);};
Would anyone be able to help??
function showIndProd(prodNum){
var indProgs = document.getElementsByClassName('indProg');
var indProgImgs = document.getElementsByClassName('indProgImg');
var indProgPs = document.getElementsByClassName('indProgP');
var progMores = document.getElementsByClassName('indProdMore');
var chosenProd = document.getElementById(["indProg"+prodNum]);
var chosenProdMore = document.getElementById(["indProdMore0"+prodNum]);
var closeBut = document.getElementById('closeProdsMore');
for (i = 0; i < indProgImgs.length; i++) {
if (prodNum != 0){
indProgs[i].style.opacity = "0.3";
indProgImgs[i].style.height = "300px";
indProgs[i].style.filter = "grayscale(100%)";
progMores[i].style.display = "none";
chosenProd.style.opacity = "1";
chosenProd.style.filter = "none";
chosenProdMore.style.display = "block";
closeBut.style.display = "inline-block";
closeBut.style.position = "relative";
chosenProd.onclick = function(){showIndProd(0);};
} else { //close all and restore to default
indProgs[i].style.opacity = "1";
indProgImgs[i].style.height = "550px";
indProgPs[i].style.display = "table";
indProgs[i].style.filter = "grayscale(0%)";
progMores[i].style.display = "none";
closeBut.style.display = "none";
}
}
}
Seems the issue is with these two line
var chosenProd = document.getElementById(["indProg"+prodNum]);
var chosenProdMore = document.getElementById(["indProdMore0"+prodNum]);
Instead of passing string you are passing array

Categories