Im trying to implement a logic whereby each time I click the button the count alternates between 1 and 0. In the following code the count is always 0 as each time I press the button the function sets the count to 0. Please help me out and thanks in advance
<html>
<head>
<script type="text/javascript">
function main(){
var button = document.getElementById('button');
count = 0;
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare count variable at global scope.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare the button in global scope. And use the bitwise operator for toggling between 0 and 1 like this..
<script type="text/javascript">
var count = 0; //global scope
function main(){
var button = document.getElementById('button');
if(button.onclick){
alert(count);
count ^= 1; //bitwise operator
}
}
</script>
^ (Bitwise XOR) as a I/O toggler
each time you click the button, main() is called. and each time you call main() you're setting count to 0 to start. Place count outside your function scope.
I agree with Ataur's answer but you might want to consider a bool for this use case as best practise.
<html>
<head>
<script type="text/javascript">
var buttonIsOn = true;
function main(){
var button = document.getElementById('button');
if(button.onclick && buttonIsOn){
alert("turning button off");
buttonIsOn = false;
}
else { // no need to check again if using bool
alert("turning button on");
buttonIsOn = true;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You should set the count to 0 outside of the function.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You need to hook click event with button and alternate between 0 & 1 on click.
function main() {
var button = document.getElementById('button');
var count = 0;
button.addEventListener("click", function() {
if (count == 0) {
alert(count);
count = 1;
}
else if (count == 1) {
alert(count);
count = 0;
}
});
}
Further make sure that main function is called on when document is in ready state or put function call to main right above closing of body tag. Something like this
<body>
<button type="button" id="button" >Click Me!</button>
<script>
main();
</script>
</body>
Related
the goal is to hide a form, do some stuff and unhide the form again. For example with this code for a progress bar I thought to do the following but the hiding/unhiding doesn't work. I'm probably overseeing something obvious.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
show_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function(){update()},10);
show_div();
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
var x = document.getElementById("do_you_see_me?");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}//end function
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
you can hide and unhide it. the problem with your code is when you trigger ready buton it will hide and then unhide the code automatically. this is becuase setInterval() function is asynchronious function. then you need call show_div() function inside the setInterval().
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
hide_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function()
{
update()
if(count>=countmax)
{
show_div();
}
},10);
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
document.getElementById("do_you_see_me?").style.display="block";
}//end function
function hide_div()
{
document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
i hope this will fix your problem.
I have this JS / HTML code. It is supposed to give you an input. When you click the button as many times as you wrote in the input then it the screen is supposed to say 'stop' but that's not happening and idk why. How can I fix this?
var text2
let count = 1;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count = count + 1;
if (count === text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'>ok</button>
<div id='div'></div>
Refactor your code like this:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='div'>ok</button>
<div id='div'> </div>
<script>
var count = 0;
function check() {
let user_input = document.getElementById('questions').value;
if (++count === parseInt(user_input)) {
document.getElementById('div').innerHTML = "stop";
}
}
</script>
</body>
</html>
This shoud do the trick:
<html>
<body>
<p>how many?<input type="text" onInput="onInput()" id="questions"></p>
<button onclick="check()" id = 'but'> ok </button>
<div id = 'div'> </div>
<script>
var text2;
let count = 0
function onInput() {
var element = document.getElementById('questions');
//replace window
text2 = element.value;
}
function check(){
count = count + 1;
console.log(count);
if (count === parseInt(text2)){
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
You are using === to compare, which checks type before comparing. count is an integer and text2 is a String, so it will always return false. Instead, first parse text2 into an integer, then compare like so:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 0;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count === parseInt(text2)) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
Or instead use == which only checks for value:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count == text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
<script type="text/javascript">
var score = 1;
}
function increase1()
{
score=score+1;
document.getElementById("clickmebtn").value = score;
}
</script>
</head>
<body>
<div id="container"><center><div id="spacer"></div><div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="increase1()" onmouseup="increase1()"><br><br><br><br></r></div></center>
</div>
</body>
</html>
Can I use pure JavaScript to make on hold button variable increase? I want to increase variable named score.
I believe you are hopping something like this-
let score = 0;
let status = false;
const scoreEl = document.querySelector('#score');
const btnEl = document.querySelector('#btn');
let interval = null;
btnEl.addEventListener('mousedown', e => {
status = true;
update();
});
btnEl.addEventListener('mouseup', e => {
status = false;
update();
});
const update = () => {
if (status) {
interval = setInterval(() => {
score++;
scoreEl.innerHTML = score;
}, 100);
} else {
if (interval) clearInterval(interval);
}
}
<div id="score">0</div>
<button id="btn">Increment</button>
On onmousedown, create a setInterval to call the function every n miliseconds
On onmouseup, remove that interval! (clearInterval)
var interval = null;
var button = document.querySelector("#clickmebtn");
var score = 0;
button.onmousedown = function(){
addCount(); // Call function right away
interval = setInterval(addCount, 500); // Start calling every 500ms
};
button.onmouseup = function(){
clearInterval(interval); // Clear the interval if button is released
};
// Add 1 to counter and set as button value
function addCount() {
button.value = ++score;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
</head>
<body>
<div id="container">
<center>
<div id="spacer"></div>
<div id="btiptsish">
<input id="clickmebtn" type="submit" value="0"><br><br><br><br>
</div>
</center>
</div>
</body>
</html>
Use the setTimeout to set an interval and loop through it in the onmousedown event listener. I have used a seperate listener in onmouseup to clear the timeout
Below you can change the time in the setTimeout to change the interval between the score increase
var score = 0;
var timer;
function increase1()
{
timer = setTimeout(function(){
score=score+1;
document.getElementById("clickmebtn").value = score;
increase1();
}, 1000);
}
function stop() {
clearTimeout(timer);
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
</head>
<body>
<div id="container"><center><div id="spacer"></div><div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="increase1()" onmouseup="stop()"><br><br><br><br></r></div></center>
</div>
</body>
</html>
I'd do this by changing your onmousedown event to [start an interval][1], which calls your increase1() method repeatedly until the [interval is cleared][2] with onmouseup.
You can do this with a busy loop (e.g. while(true)) but that would block the UI thread and your page would become unresponsive. Using intervals avoids this.
Your example, updated to use this approach:
var score = 1;
function increase1() {
score = score + 1;
document.getElementById("clickmebtn").value = score;
}
var increaseDelay = 10; // increase score once every 10ms (prevents blocking UI thread with busy loop)
var interval = null;
function turnCounterOn() {
interval = setInterval(increase1, increaseDelay);
}
function turnCounterOff() {
clearInterval(interval);
}
<div id="container">
<center>
<div id="spacer"></div>
<div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="turnCounterOn()"
onmouseup="turnCounterOff()">
<br><br><br><br>
</div>
</center>
</div>
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}
I need to display a message on mouse click. But I also need another message to be displayed on the next mouse click. The problem is that in my code both messages appear on the first mouse click.
<!DOCTYPE>
<html>
<head>
<script>
function myfunction()
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
if(obj.innerHTML=="message1")
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>
<script>
var flag=0;
function myfunction()
{
if (flag==0)
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
flag=1;}
else
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
obj1.innerHTML = "message2";
}else{
obj.innerHTML = "message1";
}
Your if would always execute because you were trying to check if obj.innerHTML == "message1" immediately after setting it to that.
Do you see that you set the innerhtml of obj to "message1" and then immediately after you check if the innerHTML is "message1" that will always be true.
You need to change the if. So it says:
if(obj.innterHTML=="message1"){
obj.innerHTML="message2";
} else {
obj.innerHTML="message1";
}
Similar to others, but what the heck:
var obj1 = document.getElementById('msg1');
var obj2 = document.getElementById('msg2');
if (obj1.innerHTML == '') {
obj1.innerHTML = 'message1';
} else {
obj2.innerHTML = 'message2';
}
function myfunction() {
var i, ele;
for(i = 1; i <= 2; i++) {
ele = document.getElementById("msg"+i);
if (ele && ele.innerHTML.length == 0) {
ele.innerHTML = 'message' + i;
return;
}
}
}
Just add a click counter to check it was first click or more then first.
<!DOCTYPE>
<html>
<head>
<script>
var $clickCount = 0;
function myfunction() {
$clickCount++;
var obj = document.getElementById("msg1");
obj.innerHTML = "message1";
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
if ($clickCount == 2) {
obj1.innerHTML = "message2";
}
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>