steady_progress steady_progress - 17 days ago 5
Javascript Question

javascript function doesn't get called

The following html-webpage contains a button. If you click the button contained in the page, the color of the button is supposed to turn red (according to the js-code). However, it does not work and I do not understand why it does not work.
In fact, nobody around me understands why it doesn't work. If somebody knows what's going on, please help me!



<!DOCTYPE html>
<html>
<body>

<h1>Please click the button below, it will turn red.</h1>

<button type="button" onclick="myFunction(this)">Set background color</button>

<script>
function myFunction(element) {
element.style.backgroundColor = "red";
}
</script>

</body>
</html>





UPDATE: the above code works, sorry for this. I had simplified my original code before posting it here. My goal was to reduce the code to the essential part.
Below you find the original code. If I press the button twice, it is supposed to turn green. However, it stays red. And I don't understand why.

<!DOCTYPE html>
<html>
<body>

<h1>Please click the button below, it will turn red.</h1>

<button type="button" onclick="setColor(this)">Set background color</button>

<script>
lastField = null;
function setColor(element) {
if (element === lastField) {
element.style.backgroundColor = "green";
}

element.style.backgroundColor = "red";

lastField = element;
}
</script>

</body>
</html>

Answer

The first time you click it, lastField is null, so the background is set to red and lastField is set to the element.

The second time you click it, lastField is the element, so the background is set to green … then the background is immediately set to red and lastField is set to the element.

The third and subsequence times are identical to the second time.

You need an else in there.

Comments