Stefan Vujic Stefan Vujic - 30 days ago 7
Javascript Question

Adding a click event listener in script not working

So I'm trying to change the color in a text box from blue to red on click, however, it's always red, the event listeners not working for some reason.

<form name="mForm">
<input type="text" name="in1">
<input type="text" name="in2">
<button name="butt1">click1</button>
<button name="butt2">click2</button>
</form>

<script type="text/javascript">
function formFun() {
var textBox1 = document.forms[0].elements[0];
var textBox2 = document.forms[0].elements[1];

var button1 = document.forms[0].elements[2];
var button2 = document.forms[0].elements[3];

textBox2.style.backgroundColor = "blue";
button1.style.backgroundColor = "blue";
button2.style.backgroundColor = "blue";

button1.addEventListener("click", changeColor());

function changeColor() {
textBox1.style.backgroundColor = "red";
}

}
</script>

Answer Source

When you call addEventListener, you need to pass a function as the second parameter. But if you think about it, you're actually passing the return value of a function call. Quite different!

button1.addEventListener("click", changeColor); is the correct usage. You're telling the event listener which function to call when an event comes in. It'll call the event handler for you. Think of your function as just any other variable you would pass into a function.