HTML, javascript Enable Disable Button - javascript

Overview: There is a Button on my webage, its a single button. When I click this button, it should call function X. If I click this button a second time, it should call function Y. Basically, this is an ON and OFF switch. this button calls a function via onclick="function X". the same onclick needs to call function Y if clicked again. I hope I made that clear.
It cannot be 2 seperate buttons. thats too easy. does anyone have any ideas ? the only flexibily I have in terms of languages is html, javacript and css. any ideas welcome.

You don't need multiple functions. Just use a boolean to toggle between 2 different parts of code.
var toggle = true;
function functionX(){
if(toggle){
// Logic for the first click
} else {
// Logic for the other click
}
toggle = !toggle; // change the toggle for the next time the button's clicked.
}

There are a few ways to do this:
Two Buttons
html
<button id="a" onclick="a()">Test</button>
<button id="b" onclick="b()" style="hidden">Test</button>
css
.hidden {
display: none;
}
js
function a() {
var buttonA = document.getElementById('a');
var buttonB = document.getElementById('b');
buttonA.classList.add('hidden');
buttonB.classList.remove('hidden');
}
function b() {
var buttonA = document.getElementById('a');
var buttonB = document.getElementById('b');
buttonB.classList.add('hidden');
buttonA.classList.remove('hidden');
}
Hold State in a var
html
<button onclick="x()">Test</button>
js
var clicked = 'b'; //initial state
function x() {
switch(clicked) {
case 'a':
clicked = 'a';
a();
break;
case 'b':
clicked = 'b';
b();
break;
default: throw 'unknown state';
}
}
function a() {
//something
}
function b() {
//something
}
Re-assign listener on click (Easier with jquery)
html
<button id="x">Test</button>
js
$(document).ready(function() {
$('#x').click(a());
});
function a() {
//do something then..
$('#x').click(b);
}
function b() {
//do something then..
$('#x').click(a);
}

try this code
var i = 0;
function fun() {
if (i == 0) {
funX();
i = 1;
} else {
funY();
i = 0;
}
}
function funX() {
console.log('x');
}
function funY() {
console.log('y');
}
<button id="test" onclick="fun()">Click</button>

Related

Compare Value's of 2 different functions for alert

Im just a beginner learning Javascript, and i have a problem.
I want to compare value's of 2 different functions. When value "kliks" is higher than value "clicks" , then alert: (...) I know what the problem is, but i dont know how to fix it.
My function code is the following:
var kliks = 0;
var clicks = 0;
function clickMe() {
kliks++;
document.getElementById("kliks").innerHTML = kliks;
}
function onClick() {
clicks++;
document.getElementById("clicks").innerHTML = clicks;
return clicks;
}
if (kliks > clicks) {
alert("Something")
}
Because the value's are in the function, the var always give 0 in the IF statement.
I tried to get both functions in 1 function, i tried to post the if statement in the functions, but i dont know how to fix it.
Hope you guys can help me!
Sorry for my horrible english btw ;)
Change the code as follows:
var kliks = 0;
var clicks = 0;
function clickMe() {
kliks++;
document.getElementById("kliks").innerHTML = kliks;
check();
}
function onClick() {
clicks++;
document.getElementById("clicks").innerHTML = clicks;
check();
}
function check() {
if (kliks > clicks) {
alert("Something")
}
}
Basically, you need to check, after each click, if klicks is greater than clicks. This is done by calling the function check() in each of clickMe and onClick functions.
You can try to encapsulate your condition checking in a function and call that function in each of your other functions:
var kliks = 0;
var clicks = 0;
function onKlik() {
kliks++;
document.getElementById("kliks").innerHTML = kliks;
checkClicks();
}
function onClick() {
clicks++;
document.getElementById("clicks").innerHTML = clicks;
checkClicks();
}
function checkClicks() {
if (kliks > clicks) {
alert("Something");
}
}
<div id="kliks" onclick="onKlik();">kliks</div>
<div id="clicks" onclick="onClick();">clicks</div>
var kliks = 0;
var clicks = 0;
function clickMe() {
kliks++;
document.getElementById("kliks").innerHTML = kliks;
compare(kliks,clicks);
}
function onClick() {
clicks++;
document.getElementById("clicks").innerHTML = clicks;
compare(kliks,clicks);
}
var compare = function(kliks,clicks){
if(kliks > clicks){
alert('something')
}
}
<div id="kliks" onclick="clickMe();">kliks</div>
<div id="clicks" onclick="onClick();">clicks</div>

In Javascript, how can I prevent the second function from running unless the first function has been invoked?

This has probably been covered before, but what I'm seeing online is confusing, or at least too advanced for a beginner like myself. Here's an example....
var funcA = function() {
alert("Button A has been pressed");
};
var funcB = function() {
if (funcA === false){
alert("press Button A");
}
else{
alert("Button B has been pressed");
}
};
var buttonA = document.getElementById('button1');
buttonA.onclick = funcA;
var buttonB = document.getElementById('button2');
buttonB.onclick = funcB;
If I click on Button A or Button B in any order, they work; but I don't want Button B to work unless Button A has been clicked first. With the code I have now, the if statement in funcB never runs, but the else statement always runs.
I might create a variable that would effectively function as a switch that you hit when you run function A. :
var funcAPressed = false;
var funcA = function() {
alert("Button A has been pressed");
funcAPressed = true;
};
var funcB = function() {
if (funcAPressed === false){
alert("press Button A");
}
else{
alert("Button B has been pressed");
}
};
var buttonA = document.getElementById('button1');
buttonA.onclick = funcA;
var buttonB = document.getElementById('button2');
buttonB.onclick = funcB;
The code block inside the following if statement will never run because funcA is not a boolean, it is a function that has no return value.
if (funcA === false){
alert("press Button A");
}
What you can do however is just declare a boolean that serves as a flag, like so:
(function() {
let called = false;
var funcA = function() {
called = true;
alert("Button A has been pressed");
};
var funcB = function() {
if (!called) {
alert("press Button A");
} else {
alert("Button B has been pressed");
}
};
var buttonA = document.getElementById('button1');
buttonA.onclick = funcA;
var buttonB = document.getElementById('button2');
buttonB.onclick = funcB;
})();
<button id="button1">button 1</button>
<button id="button2">button 2</button>
This could be dirty but can work `
var count = 0;
function funcA(){
count = 1;
}
function funcB(){
if(count == 1){
alert("OKAy!")
}else{
alert("Press Button A");
}
}
<button id="a" onclick="funcA();">A</button>
<button id= "b" onclick="funcB();">B</button>
`
I think you have already got the answer but just to add that when you do:
var funcA = function() {
alert("Button A has been pressed");
}
And later check:
if (funcA === false){
alert("press Button A");
}
Then funcA will not be false. The reason is that you have assigned a function object to funcA variable and hence it is truthy. It doesn't represent the fact that button1 has been pressed earlier or not. Javascript is different from other classical languages and hence in javascript function can be assigned to a variable. Hope it helps you learn the language better!
Just change Button B's behavior in the click handler of button A:
document.getElementById('a').onclick = () => {
alert("Button A has been pressed");
document.getElementById('b').onclick = () => {alert("Button B has been pressed") };
}
document.getElementById('b').onclick = () => { alert("press Button A") };
<button id="a">a</button>
<button id="b">b</button>

Toggle Event Listeners

I am trying to make a function that would allow me to toggle eventListener of an element.
In the example below, I have three buttons: main, on and off. When I click on the on button, the main button becomes functional. After I click off button, the main button should not work anymore (but now it still does).
Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.
Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.
(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)
// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");
// main function
var toggleButtons = function(toggleVal, button, element) {
var activateButton, clickHandler, disableButton;
// callback function for listener bellow
clickHandler = function() {
document.querySelector(element).classList.toggle("yellow");
};
activateButton = function() {
button.addEventListener("click", clickHandler);
};
disableButton = function() {
button.removeEventListener("click", clickHandler);
};
// when first argument is 1, make the button functional, otherwise disable its functionality
if (toggleVal === 1) {
activateButton();
} else {
disableButton();
}
};
// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
toggleButtons(1, mainButton, "body");
});
// this fails to disable the button
offButton.addEventListener("click", function() {
toggleButtons(0, mainButton);
});
.yellow {
background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");
var element; // declare the element here and change it from toggleButtons when needed.
function clickHandler() {
document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
button.removeEventListener('click', clickHandler);
}
function toggleButtons(value, button) {
if (value === 1) {
activateButton(button); // You missed this part
} else {
disableButton(button); // You missed this part
}
};
onButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(0, mainButton);
});
Below code helps to toggle between two functions from an eventListener:
var playmusic=false;
function playSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.currentTime = 0
audio.play()
playmusic=true;
}
function stopSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.pause()
playmusic=false;
}
window.addEventListener('keydown',
function(){playmusic?stopSound():playSound()} )

one button calls two different functions on different clicks

<script>
function one() {
blah blah blah
}
function two() {
blah blah blah
}
</script>
<button onclick="one(); two()">Click Me</button>
This will call the two functions at the same time. What I want is to call function one() on the first click and then call function two() on the second click. Calls function three() on 3rd click and so on until 7th click
I would prefer to not use jQuery if possible
You can use an IIFE to accomplish this:
var fn3 = (function() {
var first = true;
return function() {
first ? fn1() : fn2();
first = !first;
}
})();
function fn1() {
console.log(1);
};
function fn2() {
console.log(2);
};
<button onClick="fn3()">click</button>
The solution is not too complex, you can just one() and two() from another function.
var callOne = true;
function one() {
alert('Call one');
}
function two() {
alert('Call two');
}
function call(){
if(callOne) one();
else two();
callOne = !callOne;
}
<button onclick="call();">Click Me</button>
One simple way of doing this is to reassign the onclick value:
<button id="clickme">Click Me</button>
<script>
function one() {
alert('one clicked');
document.getElementById('clickme').onclick = two;
}
function two() {
alert('two clicked');
}
document.getElementById('clickme').onclick = one;
</script>
Using this trick you have the option to disable the button after calling two():
document.getElementById('clickme').onclick = null;
Toggle the click handler back to one():
document.getElementById('clickme').onclick = one;
Or do anything else you want.
I'll do it like bellow
On click of the button have a function which decides which function to call according to number of times.
<button onclick="decideFunction()">Click Me</button>
var times = 0;
var one = function(){
alert('first time');
}
var two = function(){
alert('After first');
}
var decideFunction = function(){
if(times == 0){
one();
times++;
}
else{
two();
}
}
So first time it will execute function one and second time onwards it will execute function two.
The simplest way is defining an extra variable to false(or true, of course). While our variable is false, clicking button calls first function and changes the variable to true. On second click, our onclick function checkes the variable value and calls the function which we defined for true value.
var button = document.getElementById('button');
var x = false;
button.addEventListener('click', function(){
if(!x){
alert('function 1');
x = true;
}else{
alert('function 2');
x = false;
}
})

Stop function after certain number of clicks on a certain element

OK so I am making a reaction tester, and I have a function that makes shapes appear on screen, So what I want is some sort of function were after 5 clicks on a certain element it will end a function. Is there a way of doing that? sorry if its a dumb question, its because I am new to the whole coding...
Here you go
var clickHandler = (function (e) {
var count = 0;
return function () {
count += 1;
if (count > 5) {
return;
}
// do other stuff here
}
}());
aDiv.addEventListener('click', clickHandler, false);
You Can use static variable to count how many times the object has been clicked.
and here is how you can create static variable in javascript.
You can unbind the click event once the counter reaches 5. See the example below
function test(sender) {
sender.dataset.clicked++;
console.log("I've been clicked", sender.dataset.clicked);
if (+sender.dataset.clicked === 5) {
// unbind the event
sender.onclick = null;
}
return;
}
<div onclick="test(this);" data-clicked="0">click me</div>
You may use global variable which may remain counting on click function
<script>
var globalvar = 0;
onclickfunct()
{
globalvar += 1;
if(globalvar == 5)
{
//do my work
}
else
{
//give alert
}
}
</script>

Categories

Resources