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.
Related
I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})
So right now im in the stages of making a todo list.
The stage im at is to when i click the button it adds the text i typed in the box, but then its suppose to also with a for loop store it locally.
The value entered is supposed to be stored here:
https://gyazo.com/cb156bc01383343ddaeb7b41d2e622a9
In the console u can see that the array is just empty and not showing the values like its suppose to.
This is the code section that is handling this:
var lagring = document.getElementsByClassName("produkter");
var tempArr = [];
//loopar listan
for(i=0; i<lagring.length; i++) {
tempArr.push(lagring[i].innerHTML);
}
console.log(tempArr);
The full code will be linked below.
So why isnt the value im entering into the box, when it gets added to the list(that works) but storing it in the array doesnt.
full code:
HTML:
//Kod skapad av Emil Palm
"use strict";
//Variabler
var addProdukt = document.getElementById("newtodo");
var addProduktButton = document.getElementById("newtodobutton");
var errorMessage = document.getElementById("message");
var toDoList = document.getElementById("todolist");
var i;
// Händelsehanterare
addProdukt.addEventListener("keyup", checkInput, false);
addProduktButton.addEventListener("click", addProdukt1, false);
window.onload = init;
//Initieringsfunktion
function init() {
console.log("Initierar...");
//Läs in Produktlista
loadProdukter();
// Inaktivera knappen
addProduktButton.disabled = true;
}
// Kontrollera input
function checkInput() {
console.log("Kontrollerar input...");
var input = addProdukt.value;
// Kontrollera längd
if(input.length > 4) {
errorMessage.innerHTML = "";
addProduktButton.disabled = false;
} else {
errorMessage.innerHTML = "Måste innehålla minst 5 tecken";
addProduktButton.disabled = true;
}
}
// Lägg till produkt
function addProdukt1() {
console.log("Lägger till Produkt...");
// Skapar nytt element
var input = addProdukt.value;
var newEl = document.createElement("article");
var newTextNode = document.createTextNode(input);
newEl.appendChild(newTextNode);
newEl.className = "Produkter";
// lägger till i lista
toDoList.appendChild(newEl);
addProdukt.value = "";
addProduktButton.disabled = true;
//Anropar lagring
saveProdukter();
}
// Spara produkter
function saveProdukter() {
console.log("Lagrar produktlista...");
var lagring = document.getElementsByClassName("produkter");
var tempArr = [];
//loopar listan
for(i=0; i<lagring.length; i++) {
tempArr.push(lagring[i].innerHTML);
}
console.log(tempArr);
}
//Läs in produkter
function loadProdukter() {
console.log("Läser in Produktlista")
}
<body>
<header id="mainheader">
<div class="contain">
<h1 id="logo">DT084G</h1>
</div>
<!-- /.contain -->
</header>
<div class="container">
<h2>Laboration 3 - DOM och events</h2>
<h3>Lägg till ny sak att göra</h3>
<section id="new">
<label for="newtodo">Att göra:</label><br>
<input type="text" id="newtodo">
<button class="btn" id="newtodobutton">Lägg till</button><br>
<span id="message"></span>
</section>
<h3>Saker att göra</h3>
<section id="todolist">
</section>
<button id="clearbutton" class="btn">Rensa</button>
<footer>
<p>Laborationsuppgift för kursen DT084G, Introduktion till programmering med JavaScript.</p>
</footer>
</div>
<!-- /.container -->
</body>
I have the following that is supposed to hide/show the array values with a delay of 3seconds:
function loop(s, val) {
s.style.display = val;
if (++i < s.length) {
setTimeout(loop, 3000); // call myself in 3 seconds time if required
}
};
Autocomplete.prototype.filterCategory = function(e) {
this.input.addEventListener("keyup", (e) => {
let inputVal = this.input.value,
patt = new RegExp(inputVal);
for (var i = 0; i < this.categories.length; i++) {
if(!patt.test(this.categories[i].dataset.cat)){
//this.categories[i].style.display = "none";
console.log('none');
loop(this.categories[i], 'none');
}
else {console.log('block');
loop(this.categories[i], 'block');
}
}
});
}
Short HTML:
<div class="category" data-cat="programmer, sales, manager">
<p class="h-text-cap">sales</p>
<a class="btn btn__open btn__open--blue" href="">more</a>
</div>
<div class="category" data-cat="programmer, sales, manager, vendor">
<p class="h-text-cap">sales</p>
<a class="btn btn__open btn__open--blue" href="">more</a>
</div>
<div class="category" data-cat="programmer, sales, manager, carpenter">
<p class="h-text-cap">capenter</p>
<a class="btn btn__open btn__open--blue" href="">more</a>
</div>
<div class="category" data-cat="programmer, sales">
<p class="h-text-cap">sales</p>
<a class="btn btn__open btn__open--blue" href="">more</a>
</div>
UPDATED CODE:
function loop(s, val) {
s[i].style.display = val;
if (++y < s.length) {
setTimeout(loop(s, val), 3000); // call myself in 3 seconds time if required
}
};
Autocomplete.prototype.filterCategory = function(e) {
this.input.addEventListener("keyup", (e) => {
let inputVal = this.input.value,
patt = new RegExp(inputVal),
newA = [];
for (var i = 0; i < this.categories.length; i++) {
if(!patt.test(this.categories[i].dataset.cat)){
newA.push(this.categories[i]);
loop(newA, 'none');
}
else {
loop(this.categories[i], 'block');
}
}
});
}
i is not defined
by typing a job-title "programmer", I want o hide all the data-cat that don't hold that value. At the moment it works fine in terms of logic, however they all get hidden or shown in one block as opposed to individually with a 3s delay.
<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>
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/