-3

Using this JavaScript:

function test1() { console.log('Test 1'); }
function test2() { console.log('Test 2'); }

const button = document.getElementById('button');  

button.onclick = function() { test1(); }
button.onclick = function() { test2(); }

and this HTML

<button id="button">RGB</button>

When I click on the button, only "Test 2" is displayed in the console.

Why is this the case? Why aren't both functions executed?

Ivar
  • 6,138
  • 12
  • 49
  • 61

3 Answers3

0

Look how similar those both lines look

button.onclick = function() { test1(); }
button.onclick = function() { test2(); }

To make it more clear

let a = "foo";
a = "bar";
console.log(a);

Just as we've overridden a, you're overriding button.onclick by assigning multiple times to it.

You'd usually addEventListeners nowadays instead of using onclick.

button.addEventListener('click', function() { test1(); })
button.addEventListener('click', function() { test2(); })
baao
  • 71,625
  • 17
  • 143
  • 203
0

When I click on the button, only "Test 2" is displayed in the console.

This is because second function is replacing the previous function which was assigned to onclick. You can avoid two onclick and call test2 from test1

function test1() {
  console.log('Test 1');
  test2();
}

function test2() {
  console.log('Test 2');
}

const button = document.getElementById('button');

button.onclick = function() {
  test1();
}
<button id="button">RGB</button>
brk
  • 48,835
  • 10
  • 56
  • 78
-1

When you change button.onclick it doesnot combine the previous values and the new value. Instead the previous one is replaced by new one. n

When you assign a variable to a value. The previous value is overwritten by the new one.

If you want to attach multiple functions for single event use addEventListener

function test1() { console.log('Test 1'); }
function test2() { console.log('Test 2'); }
const button = document.getElementById('button');  
button.addEventListener('click',test1) ;
button.addEventListener('click',test2) 
<button id="button">Click me</button>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73