Jan de Vries Jan de Vries - 3 months ago 20
Javascript Question

bind and unbind functions

I have 3 buttons - btn 1, 2 and 3 - with each their own function asigned to it. What I want is that button 1 has function 1 by default. But when pressing button 2, the function of button 1 has to switch to function 4. When pressing button 3, button 1 has to asigned to function 1 again. So buttons 2 and 3 have their own function, but they also have to switch the function of button 1. The code is:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<button id="button1">button 1</button>
<button id="button2">button 2</button>
<button id="button3">button 3</button>

<script>
document.getElementById("button1").addEventListener("click", myFunction1);

function myFunction1() {
alert ("1");
}

document.getElementById("button2").addEventListener("click", myFunction2);

function myFunction2() {
alert ("2");
}

document.getElementById("button3").addEventListener("click", myFunction3);

function myFunction3() {
alert ("3");
}
</script>

<script>
function myFunction4() {
alert ("4");
}
</script>


</body>
</html>

Answer

You can use if statements to assign what you want the function to do using numbers:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<button id="button1">button 1</button>
<button id="button2">button 2</button>
<button id="button3">button 3</button>

<script>
document.getElementById("button1").addEventListener("click", myFunction1);
var functionType = 1;
function myFunction1() {
  if(functionType == 1){
    alert("1");
  } else if(functionType == 4){
    myFunction4();
  }
}

document.getElementById("button2").addEventListener("click", myFunction2);

function myFunction2() {
alert ("2");
functionType=4;
}

document.getElementById("button3").addEventListener("click", myFunction3);

function myFunction3() {
alert ("3");
functionType=1; 
}
  
  function myFunction4() {
alert ("4");
}
</script>

<script>

</script>

PS: You can also use a boolean (true/false) for functionType but if your planning on adding more functionality I would use numbers.

Comments