G_G
G_G

Reputation: 33

HTML, javascript Enable Disable Button

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.

Upvotes: 0

Views: 1135

Answers (3)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7165

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>

Upvotes: 0

Rhys Bradbury
Rhys Bradbury

Reputation: 1707

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);
}

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72837

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.
}

Upvotes: 1

Related Questions