I am an absolute beginner in this field. And what i m doing is a small todo-list page.
And I am stuck in the following 'button events' part.
As in the code, I want to toggle the class of 'completed' to the ancestor div of the button clicked. However, it seems to work only for some elements.
Meaning, if the nodelist of 'finishBtn' variable has an odd number length, the class list only toggles for even number indexes and vice versa.
For example, if nodelist.length = 3, then the class list only toggles for nodelist[0]
and nodelist[2].
(However, for removeBtn variable, it works just fine)
Thank you very much for your time. I would really appreciate every reply of yours.
Cos I m stuck in this bloody thing for hours.
addBtn.addEventListener('click', (e)=> {
e.preventDefault();
if(input.value === ''){
return;
}
// adding elements to the body;
const eachTodo = document.createElement('div');
eachTodo.classList.add('eachTodo');
const textName = document.createElement('p');
textName.textContent = input.value;
const btns = document.createElement('div');
btns.classList.add('btns');
const finish = document.createElement('button');
finish.classList.add('finish');
finish.textContent = 'Finish';
const remove = document.createElement('button');
remove.classList.add('remove');
remove.textContent = 'Remove';
btns.append(finish, remove);
eachTodo.append(textName, btns);
plansDiv.append(eachTodo);
input.value = '';
//button Events
const finishBtn = document.querySelectorAll('.finish');
const removeBtn = document.querySelectorAll('.remove');
finishBtn.forEach(btn => {
btn.addEventListener('click', ()=>{
btn.parentElement.parentElement.classList.toggle('completed');
})
})
removeBtn.forEach(btn => {
btn.addEventListener('click', ()=>{
btn.parentElement.parentElement.remove();
})
})
})
This is my CSS part
.completed p {
text-decoration: line-through;
opacity: 0.8;
}
As it stands you're querying all buttons on each add and adding new listeners to them all resulting in duplicate listeners on each button that fire sequentially.
Elements with an even number of listeners attached will toggle the class an even number of times and return to the initial value.
"on" toggle-> "off" toggle-> "on"
Elements with an odd number of attached listeners toggle the class an odd number of times and appear correct at the end.
"on" toggle-> "off" toggle-> "on" toggle-> "off"
(It works for Remove because the first listener removes the element and subsequent Removes don't change that.)
Add listeners only once to each button
You can avoid this by simply adding the listeners directly to the newly created buttons. You already have references to each button and their parent element (eachTodo) in the script, so you can just add the listeners directly to them and reference the parent directly.
finish.addEventListener('click', () => {
eachTodo.classList.toggle('completed');
});
remove.addEventListener('click', () => {
eachTodo.remove();
});
const addBtn = document.getElementById('addBtn');
const plansDiv = document.getElementById('plansDiv');
const input = document.getElementById('input');
addBtn.addEventListener('click', (e) => {
e.preventDefault();
if (input.value === '') {
return;
}
// adding elements to the body;
const eachTodo = document.createElement('div');
eachTodo.classList.add('eachTodo');
const textName = document.createElement('p');
textName.textContent = input.value;
const btns = document.createElement('div');
btns.classList.add('btns');
const finish = document.createElement('button');
finish.classList.add('finish');
finish.textContent = 'Finish';
const remove = document.createElement('button');
remove.classList.add('remove');
remove.textContent = 'Remove';
btns.append(finish, remove);
eachTodo.append(textName, btns);
plansDiv.append(eachTodo);
input.value = '';
// Add listeners directly
finish.addEventListener('click', () => {
eachTodo.classList.toggle('completed');
})
remove.addEventListener('click', () => {
eachTodo.remove();
})
})
.completed p {
text-decoration: line-through;
opacity: 0.8;
}
<input type="text" id="input">
<button type="button" id="addBtn">Add</button>
<div id="plansDiv"></div>
Event delegation
A more concise solution would be to use event delegation and handle all the buttons in a single handler added to the document. Here replacing parentElement with closest('.eachTodo') to avoid the fragility of a specific ancestor depth, and checking which button was clicked using Element.matches().
document.addEventListener('click', (e) => {
if (e.target.matches('button.finish')){
e.target.closest('.eachTodo').classList.toggle('completed');
}
if (e.target.matches('button.remove')){
e.target.closest('.eachTodo').remove();
}
});
const addBtn = document.getElementById('addBtn');
const plansDiv = document.getElementById('plansDiv');
const input = document.getElementById('input');
document.addEventListener('click', (e) => {
if (e.target.matches('button.finish')){
e.target.closest('.eachTodo').classList.toggle('completed');
}
if (e.target.matches('button.remove')){
e.target.closest('.eachTodo').remove();
}
});
addBtn.addEventListener('click', (e) => {
if (input.value === '') {
return;
}
// adding elements to the body;
const eachTodo = document.createElement('div');
eachTodo.classList.add('eachTodo');
const textName = document.createElement('p');
textName.textContent = input.value;
const btns = document.createElement('div');
btns.classList.add('btns');
const finish = document.createElement('button');
finish.classList.add('finish');
finish.textContent = 'Finish';
finish.type = 'button';
const remove = document.createElement('button');
remove.classList.add('remove');
remove.textContent = 'Remove';
remove.type = 'button';
btns.append(finish, remove);
eachTodo.append(textName, btns);
plansDiv.append(eachTodo);
input.value = '';
});
.completed p {
text-decoration: line-through;
opacity: 0.8;
}
<input type="text" id="input">
<button type="button" id="addBtn">Add</button>
<div id="plansDiv"></div>
Note that you can also avoid the necessity of e.preventDefault() by specifying type="button" when you create your buttons. see: The Button element: type
Related
The idea that the user writes a todo, and I will be displayed in a div, if you click at the div the writing will be strikes through, but if you hover will be a small div with a trash icon displayed. My problem is that every time I click on the child element the written part of the parent div will be striked through. How can I prevent the child from acting the same as the parent? I write event.stopPropagation(); but doesn't work.
let text_field = document.getElementById("fname");
let count = 0;
text_field.addEventListener("keypress", function(event) {
if(event.key === "Enter") {
count++;
console.log(count);
event.preventDefault();
let block_to_insert = document.createElement('div');
block_to_insert.id = "div-created"+count+"";
let text_to_insert = document.getElementById('fname').value;
let text=block_to_insert.innerHTML = ''+text_field.value;
block_to_insert.classList.add('todo-div-todo');
let where_to_insert = document.getElementById('outer-div');
where_to_insert.appendChild( block_to_insert );
block_to_insert.onclick = function(e){
block_to_insert.style.setProperty("text-decoration", "line-through");
}
block_to_insert.onmouseover = function(){
let delete_div = document.createElement('div');
let text=delete_div.innerHTML = '<i class="fa-solid fa-trash" style="color:white"></i>';
delete_div.classList.add('delete-todo');
delete_div.id = "delete-div"+count+"";
let place_to_insert = document.getElementById(block_to_insert.id);
place_to_insert.appendChild( delete_div );
document.getElementById("delete-div"+count+"").addEventListener('click',function (event){
event.stopPropagation();
event.preventDefault();
},true);
}
}
});
I’m new to Js.. and I’m trying to change the inner Text of a button to toggle on click between On and Off using addEventListener method.
const btn = document.getElementsByClassName("btn")[0];
const btn2 = document.createTextNode("Off");
btn.addEventListener.toggle("click", modifiedText() {
// enter code here
});
ModifiedText() {
// enter code here
}
<button class=“btn”>On</button>
Just addEventListener on button and get or set the text inside button using textContent property.
const button = document.querySelector(".btn");
button.addEventListener("click", function clickHandler( e ) {
const btnText = e.target.textContent;
if( btnText.toLowerCase() === "on") e.target.textContent = "Off";
else e.target.textContent = "On"
})
<button class="btn">On</button>
I am trying to make a calendar web application and want to save a users' state using localstorage. I have tried using two methods (innerHTML as well as a javascript DOM-to-JSON; https://github.com/azaslavsky/domJSON), but each removes the button's onclick event.
I believe the problem is that it is stringifying only the innerhtml, which for some reason doesnt have my onlick event listed (although the onlick event fires). What should I do so that a user can reload the page and still use the buttons.
Here is an example that shows the button stop working (delete cache and website cookies/data to make the button work again):
https://codepen.io/samuel-solomon/pen/XWdzKjd?editors=1011
window.pageState;
$(document).ready(function(){
let div = document.getElementById("div")
window.pageState = JSON.parse(localStorage.getItem('pageState'));
if (window.pageState === null) {
let btn = document.createElement('button')
btn.innerText = "Hello";
btn.style = "height: 100px";
btn.onclick = function (btn) {change_text(btn)}.bind(null, btn);
div.appendChild(btn);
window.pageState = {state: div.innerHTML};
}
else {div.innerHTML = window.pageState.state}
});
function change_text(btn) {
let div = document.getElementById("div");
if (btn.innerText === "Hello") {btn.innerText = "Goodbye";}
else if (btn.innerText === "Goodbye") {btn.innerText = "Hello";}
localStorage.setItem('pageState', JSON.stringify(window.pageState));
}
Here is my wbesite where the problem exists (Ex: double click 'Ae 101A' and double click it in the calender. it should disappear. Now add it again and reload the page. Now it doesnt disappear on double click):
https://turtle-pond.com/
It seems you are using jQuery. For hooking events to dynamically created elements, I suggest the selector filtering approach: instead of binding the click event on the button element itself, listen for the click event on the parent container (or even the document) and filter by the button's selector. Here is how:
window.pageState;
$(document).ready(function(){
let div = document.getElementById("div")
$(document).on('click', "#my-button", function (event) {
const btn = event.target; // or btn = document.getElementById("my-button");
change_text(btn);
});
window.pageState = JSON.parse(localStorage.getItem('pageState'));
if (window.pageState === null) {
let btn = document.createElement('button')
btn.innerText = "Hello";
btn.style = "height: 100px";
btn.id = "my-button";
div.appendChild(btn);
window.pageState = {state: div.innerHTML};
}
else {div.innerHTML = window.pageState.state}
});
function change_text(btn) {
let div = document.getElementById("div");
if (btn.innerText === "Hello") {btn.innerText = "Goodbye";}
else if (btn.innerText === "Goodbye") {btn.innerText = "Hello";}
localStorage.setItem('pageState', JSON.stringify(window.pageState));
}
Read more about this on jQuery documentation and here.
all
I am currently practicing my coding skills and am making a simple footer selection webpage.
I have four footers with different looks that are set to "display:none" initially. Then, I have four buttons, each one corresponding to its footer type. When the button is clicked, it displays the footer.
Now I just want to know how do I write a cleaner Javascript than what I currently have. Thank you as always.
var footer1 = document.getElementById('footer1');
var footer2 = document.getElementById('footer2');
var footer3 = document.getElementById('footer3');
var footer4 = document.getElementById('footer4');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
btn1.onclick = function(e) {
console.log('You clicked button1');
e.preventDefault();
footer1.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn2.onclick = function(e) {
console.log('You clicked button2');
e.preventDefault();
footer2.style.display = 'block';
footer1.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn3.onclick = function(e) {
console.log('You clicked button3');
e.preventDefault();
footer3.style.display = 'block';
footer2.style.display = 'none';
footer1.style.display = 'none';
footer4.style.display = 'none';
}
btn4.onclick = function(e) {
console.log('You clicked button4');
e.preventDefault();
footer4.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer1.style.display = 'none';
}
You can just use Arrays like this:
let buttons = [ 'btn1', 'btn2', 'btn3', 'btn4' ];
let footers = [ 'footer1', 'footer2', 'footer3', 'footer4' ];
buttons.forEach((btn, index) => {
// Please note that you might want to use addEventListener instead of onclick
document.getElementById(btn).addEventListener('click', (event) => {
event.preventDefault();
let button = 'button' + (index + 1);
alert('You clicked ' + button);
footers.forEach((footer, index_f) => {
let f = document.getElementById(footer);
if(index_f === index) {
f.style.display = 'block';
}
else {
f.style.display = 'none';
}
});
});
});
To make things even more interesting, you can play with querySelectorAll and custom attributes. You could, for example, add the classes custom-button to your buttons and custom-footer to your footers, and on each button add a data-footer attribute pointing to the id of the corresponding footer. Then, you could do this:
document.querySelectorAll(".custom-button").forEach((button) => {
button.addEventListener('click', (event) => {
document.querySelectorAll(".custom-footer").forEach(footer => footer.style.display = 'none');
let footer = button.getAttribute("data-footer");
document.getElementById(footer).style.display = 'block';
});
});
Quite shorter.
There is a common way to do this.
Share a class (foo) between all of the elements you want to group into your show/hide radio button-like functionality.
Then use one function, like
function handler = function(e) {
var foos = document.getElementsByClass("foo");
// make all foos display="none"
var target = targets[e.target]; //get the footer to show from the target button
target.style.display = "block";
}
You can use attribute selector to loop over elements.
[attributeName="value"]
^: Means starts with
$: Ends with
This way, your logic is generic and does not requires you to maintain any list of IDs
Idea:
You can create a pattern where every button id will correspond to visibility to necessary footer. Better idea would be to use data attribute(data-<attr name>) but you can work with ids for now.
Loop over all the buttons and add handler using addEventListener. onClick is a property, so assignment will erase/ override previous value. You can either have inline anonymous function or a named function if you have too many buttons.
In this handler, loop over all footers and hide them.
Fetch index using this.id and show necessary footer. Its always better to use classes for such actions instead of setting styles.
var buttons = document.querySelectorAll('[id^="btn"]');
Array.from(buttons, (button) => {
button.addEventListener('click', function(event) {
const footers = document.querySelectorAll('[id^="footer"]');
Array.from(footers, (footer) => footer.style.display = 'none' );
const index = this.id.match(/\d+/)[0];
document.getElementById(`footer${index}`).style.display = 'block';
})
})
div[id^="footer"] {
width: 100px;
height: 100px;
border: 1px solid gray;
margin: 10px;
}
<div id="footer1"> Footer 1 </div>
<div id="footer2"> Footer 2 </div>
<div id="footer3"> Footer 3 </div>
<div id="footer4"> Footer 4 </div>
<button id="btn1"> Button 1 </button>
<button id="btn2"> Button 2 </button>
<button id="btn3"> Button 3 </button>
<button id="btn4"> Button 4 </button>
References:
Attribute Selector - MDN
I want to add an event listener to the checkbox that is created within an <li>
When the event is triggered I want to check if it is checked or unchecked
From my understanding the event for a checkbox is "onChange" and the property is "checked" but my solution is not working.
Can someone please explain to me why this solution does not work?
New to JavaScript so please explain in the most simple way.
JavaScript only please
Thank you in advance
HTML
<body>
<div class="wrapper">
<ul id="taskList">
</ul>
<div id="add-task-area">
<input type="text" id="addTaskInput" value="">
<button id="addTaskButton">Add Task</button>
</div>
</div>
</body>
JAVASCRIPT
let taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
const addTask = () => {
if (addTaskInput.value != " ") {
let taskItem = document.createElement("li");
let taskText = document.createElement("span");
taskText.textContent = addTaskInput.value;
let checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkBox");
checkBox.setAttribute("class", "checkbox");
let removeItem = document.createElement("button");
removeItem.setAttribute("class", "remove");
removeItem.textContent = "Delete";
taskList.appendChild(taskItem);
taskItem.appendChild(taskText);
taskItem.appendChild(checkBox);
taskItem.appendChild(removeItem);
addTaskInput.value = " ";
};
}
addTaskButton.addEventListener("click", addTask);
addTaskInput.addEventListener("keydown", (event) => {
if (event.keyCode == 13) {
addTask();
}});
let checkbox = document.querySelectorAll(".checkbox")
checkbox.addEventListener("onChange", test);
const test = () => {
if (checkbox.checked) {
alert("checked");
} else {
alert ("unchecked")
}
}
I am working on the same problem and managed to get it figured out!
You can bind event handlers to dynamically created elements the same way you assign an id to them, such as by doing 'li.onclick = checkCount;', where checkCount is the name of the function you want to assign to the handler.
After a lot of time and effort, I created a function that checks the state of checkboxes, pushes the number that are checked to an array, and returns the length of the array(aka the dynamically clicked checkboxes) within a span tag.
When you add the event listener to the checkbox, it is important to state that the other function is false, or else the binding will not work. I have attached my code below, I hope it is helpful to you.
const list = document.getElementById("todo-list");
//creates new li and checkboxes
function newTodo(evt) {
//stops page from reloading every time
evt.preventDefault();
const input = document.getElementById("todo-text").value;
const li = document.createElement("li");
li.appendChild(document.createTextNode("- " + input));
list.appendChild(li);
document.getElementById("todo-text").value = "";
var checkbox = document.createElement('input');
checkbox.type= "checkbox";
checkbox.value = 1;
checkbox.class = "todo";
li.appendChild(checkbox);
li.onclick = checkCount;
}
// binds event listener to call first function
const form = document.getElementById("btn").addEventListener('click', newTodo);
//specifies this will call only 2nd function since 1st function has finished
check = document.getElementsByClassName('todo');
for (var i = 0; i < check.length; i++) {
check[i].addEventListener('click', newTodo, false);
}
const checkCount = function () {
var selected = [];
var span = document.getElementById('item-count');
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkboxes.length; i++) {
selected.push(checkboxes[i]);
}
span.innerHTML = selected.length;
};
It doesn't work because the checkbox doesn't exist by the time you are adding the event listener: checkbox.addEventListener("onChange", test).
You can try adding the event listener right after you create the checkbox:
...
var checkbox = document.createElement('input');
checkbox.addEventListener("onChange", test) // <-- add this line
checkbox.type= "checkbox";
...