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>
Related
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
i'm newbie in JS.
as in the title, I want to create a disable button when the condition is met based on the following code:
<input class="input" type="text">
<button class="button">Click Me</button>
<script>
let input = document.querySelector(".input");
let button = document.querySelector(".button");
button.disabled = true;
input.addEventListener("change", stateHandle);
function stateHandle() {
if(document.querySelector(".input").value === "") {
button.disabled = true;
} else {
button.disabled = false;
}
}
</script>
value on input is auto generated after 500ms. the code above works if after the input value appears and then I enter any number. what I want is when the input value appears then the button will automatically be in the enable position.
Based on #David's answer, I added new Events and dispatch them later.
This is the updated code :
<script >
let input = document.querySelector("#input");
let button = document.querySelector("#button");
button.disabled = true; //setting button state to disabled
const event = new Event("change"); //adding new event
input.addEventListener("change", stateHandle);
function stateHandle() {
var t = document.getElementById("jarak").value,
check = "luar";
if (new RegExp('\\b' + check + '\\b').test(t)) {
button.disabled = true; //button remains disabled
} else {
button.disabled = false; //button is enabled
}
}
setTimeout(function() {
input.dispatchEvent(event); //dispatching event after 700ms
}, 700);
</script>
I have recently started learning JavaScript, and I'd like to make a button, with a function, which changes the innerHTML on click. On the first click it changes the text, but after that nothing. Any ideas how could I fix that? Here is the code so far:
let Button = document.getElementById("Btn");
Button.onclick = function change() {
let turnedOn = false;
if (Boolean(turnedOn) == false) {
Button.innerHTML = "START";
turnedOn = true;
} else {
Button.innerHTML = "STOP";
turnedOn = false;
}
}
<Button id="Btn">STOP</button>
You have to set the turnedOn flag outside of the click method, otherwise it will always be false on click.
Also you're setting the flag turnedOn inside the if-else statement in a reversed way.
Note: As you are only changing the text, you can use textContent
const button = document.getElementById("btn")
let turnedOn = false
button.addEventListener('click', e => {
if (turnedOn) {
turnedOn = false
e.currentTarget.textContent = 'Start'
} else {
turnedOn = true
e.currentTarget.textContent = 'Stop'
}
})
<button id="btn">Start</button>
The problem is that you are setting the turnedOn variable to false at the start of the function.
You can look at the HTML to find what the current state of the button and then decide to turn the button on or off.
<button id="Btn">START</button>
<script>
let Button = document.getElementById("Btn");
Button.onclick = function change () {
if(Button.innerHTML == "START")
{
Button.innerHTML = "STOP";
}
else
{
Button.innerHTML = "START";
}
}
</script>
Using javascript and do'nt jquery
<button id="btnTest" onclick="myclick()">Click OFF</button>
<script>
function myclick() {
var btnTest = document.getElementById("btnTest");
if(btnTest.innerHTML == "Click OFF"){
btnTest.innerHTML = "Click ON";
} else {
btnTest.innerHTML = "Click OFF";
}
}
</script>
The issue is that your turnedOn variable only exists within the click handler function. So it is set again to the same value on every click. You could make a global variable or :-
Create a little ToggleButton object. To encapsulate the logic for toggling the button. It can toggle itself or other elements can toggle it.
<html>
<body>
<button id="toggleButt">Toggle</button>
<button id="toggleOtherButt">Toggle</button>
</body>
<script>
function ToggleButton(elem) {
this.elem = elem;
this.on = false;
this.render();
elem.addEventListener("click", () => this.toggle());
}
ToggleButton.prototype.toggle = function() {
this.on = !this.on;
this.render();
}
ToggleButton.prototype.render = function() {
this.elem.textContent = (this.on) ? "On" : "Off";
}
const but = new ToggleButton(document.getElementById("toggleButt"));
document.getElementById("toggleOtherButt").addEventListener("click", () => but.toggle());
</script>
</html>
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