-2

At the moment i have two buttons one that changes the text to red (default) and the other when clicked changes it to green. Instead of having two buttons I need one button to say green when the text appears red so when you click on the green button it changes the colour to green and then the same button says red now and when clicked it'll change the text to red

THIS IS MY SCRIPT:

function change1() { 
 txt = document.getElementById("txt");
 txt.style.color = 'green';
}

    function change2() { 
    txt = document.getElementById("txt");
    txt.style.color = 'red';
}

And these are my buttons

<input type="button" value="Green" onclick="change1()" id="btn">

<input type="button" value="Red" onclick="change2()" id="btn">
Valerie
  • 3
  • 2

2 Answers2

2

You could do it easy with an if statement asking for style.color property:

function change() { 
  txt = document.getElementById("txt");
  if (txt.style.color === 'green'){
        txt.style.color = 'red';
  }
  else {
    txt.style.color = 'green';
  }
}

Is not a good practice attach your JavaScript in the HTML element, instead that you can retrieve the button by code and then use the addEventListener method to attach the change function to the click event, check out this codepen to see how it works.

ianaya89
  • 4,153
  • 3
  • 26
  • 34
  • thank you thats working for me really appreciate it would i do an if statement again to change the name in the button from red to green also – Valerie Nov 24 '14 at 20:38
  • @Valerie Great, check out the codepen, I have updated it to fit your requirement. (http://codepen.io/ianaya89/pen/QwbNQg) – ianaya89 Nov 24 '14 at 20:42
0

Script Adjustment

The easiest method is to use the current value of the button to determine which action to take:

function colorChange(button1) {
    var txt = document.getElementById("txt");

    if (button1.value == "Green") {
        txt.style.color = 'green';
        button1.value == "Red";
    } else {
        txt.style.color = 'red';
        button1.value == "Green";
    }
}

Alternate

You may instead use a global variable to track the state of the button, but this is a less desirable solution:

var txt;
var colorButtonIsGreen = true;

function colorChange() {
    if(!txt) txt = document.getElementById("txt");

    if (colorButtonIsGreen) {
        txt.style.color = 'green';
        button1.value == "Red";
    } else {
        txt.style.color = 'red';
        button1.value == "Green";
    }

    colorButtonIsGreen != colorButtonIsGreen;
}

HTML:

Slightly adjusted original HTML:

<input type="button" value="Green" onclick="colorChange(this);" id="btn">
Tony Chiboucas
  • 5,505
  • 1
  • 29
  • 37