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>
Related
I created a click event that opens a previously 'hidden' div and closes it again once you click the same button.
However, it only runs once (one open and one close) - I'm at a loss to explain why it doesn't work if I click it again.
let readMore = document.getElementById('clickAbout');
let moreInfo = document.getElementById('about');
let changeSepa = document.getElementById('sepChange');
readMore.addEventListener('click', function(){
changeSepa.style.height = '2rem';
if (moreInfo.className == "") {
moreInfo.className = "open";
moreInfo.style.display = 'block';
} else {
moreInfo.style.display = 'none';
}
});
this happens because you're checking if className == "", but you are modifying the className to be "open". On the second click it checks the className which is now "open" and goes to the else block. On the third click you expect for it to go into the first block but the className is still "open".
For an easy fix just change the className in the else block
else {
moreInfo.className = "";
moreInfo.style.display = 'none';
}
Also i suggest you make use of the classList property on elements
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
using the class list it could look like this:
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
if (moreInfo.className == "") {
moreInfo.classList.add("open");
moreInfo.style.display = "block";
} else {
moreInfo.classList.remove("open");
moreInfo.style.display = "none";
}
});
Or even
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
moreInfo.classList.toggle("open");
if (moreInfo.className == "") {
moreInfo.style.display = "block";
} else {
moreInfo.style.display = "none";
}
});
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’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 created buttons with different values in my HTML. I am trying to output these values when clicked on. I am making use of querySelectorAll and eventListeners but it keeps outputing undefined.
let buttons = document.querySelectorAll('button');
function showNumber() {
if (buttons.value != 5) {
document.getElementById('screen').innerHTML = buttons.value;
} else {
document.getElementById('screen').innerHTML = 5;
}
}
buttons.forEach(buttons => {
buttons.addEventListener("click", () => {
showNumber()
});
});
You can do it like this:
const
buttons = document.getElementsByTagName("button"),
screen = document.getElementById('screen');
Array.from(buttons).forEach(button =>
button.addEventListener("click", showNumber));
function showNumber(event) { // Listener can access its triggering event
const button = event.target; // event's `target` property is useful
if (button.value != 5) { screen.innerHTML = button.value; }
else { screen.innerHTML = 5; }
}
<button value="5">Button 1</button>
<button value="42">Button 2</button>
<p id="screen"></p>
But you might consider employing event delegation:
const
container = document.getElementById('container'),
screen = document.getElementById('screen');
container.addEventListener("click", showNumber); // events bubble up to ancestors
function showNumber(event) {
const clickedThing = event.target;
if(clickedThing.tagName == 'BUTTON'){ // makes sure this click interests us
screen.innerHTML = clickedThing.value;
}
}
<div id="container">
<button value="5">Button 1</button>
<button value="42">Button 2</button>
</div>
<p id="screen"></p>
in your foreach loop you need to pass back the button to your function
let buttons = document.querySelectorAll('button');
function showNumber(button) {
if (button.value != 6) {
document.getElementById('screen').innerHTML = button.value;
} else {
document.getElementById('screen').innerHTML = 5;
}
}
buttons.forEach(button => {
button.addEventListener("click", () => {
showNumber(button)
});
});
<button value=10>10</button>
<button value=8>8</button>
<button value=6>6</button>
<button value=4>4</button>
<button value=2>2</button>
<div id='screen'></div>
The issue is that buttons is the whole array of buttons, not just the clicked button.
To access the button that was clicked, the simplest way is to use this. Inside an event handler, this points to the element that triggered the event (i.e. the button that was clicked), as long as we bind the function showNumber directly to the event handler (and not calling showNumber() from an anonymous function like in your initial code), i.e.:
button.addEventListener("click", showNumber);
So, binding showNumber directly to the event handler and using this, this is what we can do:
let buttons = document.querySelectorAll('button');
function showNumber() {
if (buttons.value != 5) {
document.getElementById('screen').innerHTML = this.value;
} else {
document.getElementById('screen').innerHTML = 5;
}
}
buttons.forEach(button => {
button.addEventListener("click", showNumber);
});
<p id="screen"></p>
<button value="1">1</button>
<button value="10">10</button>
I now have this onclick function:
<p onclick="open3()" >Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.</p>
function open3 ()
{
document.getElementById("c").style.display = "block";
}
What I want is that when I clicked on open three that it somehow changes it's value so I can click on it again to set style.display to none.
I tried this with a Boolean that set's it to true or false and then changes that but that didn't work
You can add an if statement that checks the current value of the applied style and changes it appropriately.
Using this approach you don't need to declare (and keep) any additional variable in your code, while still being able to achieve the desired effect.
An example is shown below.
function open3 () {
var c = document.getElementById('c');
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Try using a check in the function:
function open3 () {
var c = document.getElementById("c");
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Using pure Javascript:
function open3 ()
{
if (document.getElementById("c").style.display == "block")
document.getElementById("c").style.display = "none";
else
document.getElementById("c").style.display = "block";
}
Or you can use jQuery instead:
function opne3()
{
$("#c").toggle();
}
Hope it helps.
My approach is slightly different and creates a toggler function that returns a function to toggle whatever elements you pass into it with an initial state. You can keep reusing this function whenever you need to toggle an element so you don't repeat code.
var toggler = function(el, init) {
var flag = init;
return function(e) {
flag = !flag;
el.style.display = flag ? 'block' : 'none';
};
}
Create a new function passing in the element to be toggled and its initial state.
var toggleC = toggler(document.querySelector('#c'), false);
Remove the inline JS (best practice) and use addEventListener to target the element instead.
document.querySelector('#clicker').addEventListener('click', toggleC);
DEMO
A short version of the if/else answers on this page:
function open3 () {
var c = document.getElementById('c');
c.style.display = (c.style.display == 'block' ? 'none': 'block');
}
Try this
HTML:
<p id="togglethingy">Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.
CSS:
#togglethingy{
display:block;
}
jQuery:
$(function(){
var $tog_ele = $("#togglethingy")
$tog_ele.click(function() {
$tog_ele.toggle();
});
});