I want to show/hide div with children on button click, but not other same divs in different parent blocks.
Sorry for my bad explanation and js knowledge, maybe the code can speak better:
for (a = 0; a < document.querySelectorAll("#hidereplies").length; a++) {
var btn = document.querySelectorAll("#hidereplies")[a];
btn.onclick = function () {
for (var y = 0; y < document.querySelectorAll(".reply_comments").length; y++) {
var reply = document.querySelectorAll(".reply_comments")[y];
reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
}
};
}
Demo on jsfiddle.
There's a few things you're doing wrong.
First, in your HTML, don't use an ID more than once. You've given your buttons the same ID.
Next, assign your querySelector results to an array and iterate the array.
Third, you need to scope your query. You're checking for elements on the document so everything gets pulled in rather than being scoped to the current div.
//note that I've changed from an ID to a class for your buttons
var buttons = document.querySelectorAll(".hidereplies");
for (a = 0; a < buttons.length; a++) {
var btn = buttons[a];
btn.onclick = function (event) {
var btn = event.currentTarget; //get the current button clicked
var comments = btn.parentNode.querySelectorAll(".reply_comments"); //scope the search
for (var y = 0; y < comments.length; y++) {
var reply = comments[y];
reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
}
};
}
HTML
<div class="comments_list">
<div class="comment_item">
<div class="comment_body">test1 - comments</div>
<input type="button" class="hidereplies" value="show replies" />
<div class="reply_comments">
<div class="comment_body">want to hide only current ".reply_comments"</div>
</div>
</div>
<div class="comment_item">
<div class="comment_body">test2 - comments</div>
<input type="button" class="hidereplies" value="show replies" />
<div class="reply_comments">
<div class="comment_body">but not all</div>
</div>
</div>
<div class="comment_item">
<div class="comment_body">test3 - no comments</div>
<div class="reply_comments"></div>
</div>
</div>
Your updated fiddle - http://jsfiddle.net/yhtKa/4/
Related
I'm trying to do a accordion when the click on "show" to show the full profile from a list of profiles and close it with another button.
So far what I've done
<div class="short-pro">
<button class="show">Full Profile</button>
</div>
<div class="full-pro">
<button>close</button>
</div>
<div class="short-pro">
<button class="show">Full Profile</button>
</div>
<div class="full-pro">
<button>close</button>
</div>
<div class="short-pro">
<button class="show">Full Profile</button>
</div>
<div class="full-pro">
<button>close</button>
</div>
Script:
var show = document.getElementsByClassName('show');
var full= document.getElementsByClassName('full-pro');
for (i = 0; i < accbtn.length; i++) {
show[i].addEventListener("click", activeBtn());
}
function activeBtn() {
for (i = 0; i < active.length; i++) {
full[i].classList.add("active");
}
}
Note: close button not tried yet.
I hope you get the idea of what I'm trying to achieve. Any help would be highly appreciated!
You have several problems:
You should mark variable i as let
You should pass i to activeBtn function
So, you code should be like this:
var show = document.getElementsByClassName('show');
var full = document.getElementsByClassName('full-pro');
var close = document.getElementsByClassName('close');
for (let i = 0; i < show.length; i++) {
show[i].addEventListener("click", function() {
activeBtn(i);
});
}
for (let i = 0; i < close.length; i++) {
close[i].addEventListener("click", function() {
deactiveBtn(i);
});
}
function activeBtn(i) {
full[i].classList.add("active");
}
function deactiveBtn(i) {
full[i].classList.remove("active");
}
You can see full example in sandbox: https://jsfiddle.net/73ktn6hc/3/#&togetherjs=t0jU1L4mI2
Would I be able to add a remove button to replace the add button as of the image below and remove the values in that row from the array object that I have declared whenever I remove a certain row?
Image of the html (Partly)
Before Clone
After Clone
Desired Result
Html page
<div id="selections">
<div class="form-group row controls selection">
<label for="selection01" class="col-sm-2 col-form-label">Selection Pair</label>
<div class="col-sm-2">
<select class="form-control selection01" id="selection010" placeholder="Selection 01" onchange="addNewSelection()"></select>
</div>
<div class="col-sm-2">
<select class="form-control selection02" id="selection020" placeholder="Selection 02" onchange="addNewSelection()"></select>
</div>
<div class="col-sm-2">
<input type="number" min="0.00" max="10000.00" step="1.00" class="form-control" id="productQuantity0" placeholder="Quantity">
</div>
<div class="col-sm-2">
<input type="button" class="btn btn-success" id="addSelection" value="Add Selection" onclick="addNewSelectionPair()"></button>
</div>
</div>
</div>
Script
function addNewSelectionPair() {
// Get all selections by class
var selection = document.getElementsByClassName('selection');
// Get the last one
var lastSelection = selection[selection.length - 1];
// Clone it
var newSelection = lastSelection.cloneNode(true);
// Update the id values for the input
newSelection.children[1].children[0].id = 'selection01' + selection.length;
newSelection.children[2].childrne[0].id = 'selection02' + selection.length;
newSelection.children[3].children[0].id = 'productQuantity' + selection.length;
// Add it to selectionss
document.getElementById('selections').appendChild(newSelection)
}
function getValues() {
// Get all selections by class
var selections = document.getElementsByClassName('selection');
var values = [];
for(var i = 0; i < selections.length; i++) {
// Add the values into the array
values.push([
document.getElementById('selection01' + i).value,
document.getElementById('selection02' + i).value
document.getElementById('productQuantity' + i).value
]);
}
return values;
}
This script will duplicate the last row of inputs. It will also collect the inputs and store their values in a 3d array to process.
function addSection() {
//Get all sections by class
var sections = document.getElementsByClassName('section');
//Get the last one
var lastSection = sections[sections.length - 1];
//Clone it
var newSection = lastSection.cloneNode(true);
//Add it do sections
document.getElementById('sections').appendChild(newSection);
//Recalucate the Ids for the removal
//Ids all get shifted after adding or removing a section
calcRemovalIds();
}
function getValues() {
//Get all inputs by class
var sectionsOne = document.getElementsByClassName('section01');
var sectionsTwo = document.getElementsByClassName('section02');
var values = [];
//Loop the inputs
for(var i = 0; i < sectionsOne.length; i++) {
//Add the values to the array
values.push([
sectionsOne[i].value,
sectionsTwo[i].value
]);
}
return values;
}
function removeSection(id = undefined) {
//Get all sections by class
var sections = document.getElementsByClassName('section');
//If there is only one row left, just skip
if (sections.length == 1) return true;
//If not id was given, remove the last row
if (id == undefined) id = sections.length - 1;
//Get the last one
var lastSection = sections[id];
//Remove it
lastSection.parentNode.removeChild(lastSection);
//Recalucate the Ids for the removal
//Ids all get shifted after adding or removing a section
calcRemovalIds();
}
function calcRemovalIds() {
var btns = document.getElementsByClassName('button');
for (var i = 0; i < btns.length; i++) {
//Check if its the last button
if (i + 1 == btns.length) {
//Make it a addSection button
btns[i].innerHTML = '+';
btns[i].setAttribute('onclick', 'addSection()');
} else {
//Make is a removeSection button
btns[i].innerHTML = '-';
btns[i].setAttribute('onclick',
'removeSection(' + i +')'
);
}
}
}
<div>
<div>
<h2>Product</h2>
<input id="product" placeholder="Product" />
</div>
<div id="sections">
<div class="section">
<input class="section01" placeholder="Section One" />
<input class="section02" placeholder="Section Two" />
<button class="button" onclick="addSection()">+</button>
</div>
</div>
</div>
<button onclick="
document.getElementById('values').innerHTML = JSON.stringify(getValues());
">Get Values</button>
<div id="values"></div>
Hi,
can anyone tell me why everytime i click in the yellow button console log shows me the value false?? (should be alternately false right false right etc after every click)
where's mistake?
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
var flag = true;
if (flag) {
flag = false;
console.log(flag);
} else {
flag = true;
console.log(flag);
}
});
}
<section class="cursos-de-ingles">
<article class="main-cdi">
<div class="cdi cdi-one">
<div class="cdi-header">
<img src="img/numero1.png" alt="">
</div>
<div class="cdi-par">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de cursos de Inglés General</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
</div>
<!--cdi-one-->
<div class="cdi cdi-two">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de los cursos de Inglés Académico</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
<!--cdi-two-->
<div class="cdi cdi-three">
<div class="cdi-header">
</div>
<div class="cdi-par">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de los cursos individuales</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
</div>
<!--cdi-three-->
Move your flag outside of eventListener and for loop, because on every click or loop you will set the flag to true.
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
var flag = true;
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
if (flag) {
flag = false;
console.log(flag);
} else {
flag = true;
console.log(flag);
}
});
}
but if you want a different flag for different clicks use a map instead:
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
var flags = {};
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
if (flag[i]) {
flag[i] = false;
console.log(flag[i]);
} else {
flag[i] = true;
console.log(flag[i]);
}
});
}
This is because the flag is always set as true when the click happens, therefore it keeps setting itself back to false. The declaration of the flag should be moved outside of the click handler.
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
function randomQuote () {
var array = [1,20,50,100];
}
document.getElementById("btn").onclick = randomQuote;
document.getElementById("par").innerHTML = array[0];//then on another btn click array[1]...
for(var i=0; i<array.length;i++){
quote[i];
}
On "btn" click number 1 from array is shown in "par" paragraph
on another btn click number 2 shows up and 1 dissapear, and so on...
Use counter cpt as index to loop through the array and show the values :
var array = [1,20,50,100];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
function randomQuote ()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
Minified version could be :
function randomQuote ()
{
document.querySelector("#par").innerHTML = array[cpt<array.length-1?++cpt:cpt=0];
}
Snippet using Random color as you comment say :
var array = ["Quotes 1","Quotes 2","Quotes 3","Quotes 4"];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
//Init Random Color before click
getRandomColor();
function randomQuote()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
function getRandomColor()
{
document.querySelector("#par").style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
}
<div id="wrapper">
<p id="par"></p>
<button id="btn" onClick="randomQuote();getRandomColor()">Next quote</button>
</div>
Is this what you want?
var counter = 0;
function randomQuote () {
var array = [1,20,50,100];
document.getElementById("par").innerHTML(array[counter++]);
}
save the index, increment it on each click and then reset it when its undefined.
var index = -1;
function randomQuote() {
var array = [1, 20, 50, 100];
document.getElementById('par').innerText = (array[++index] || array[index=0]);
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.