'Javascript event handler won't change another element's event handler

I have two divs, div1 and div2. When div2 is clicked, I want to change the "onmouseover" handler for div1. Here is fiddle code (https://jsfiddle.net/au43obnz/2/):

<div id='div1'
onmouseover='this.style.color=`purple`'
onmouseout='this.style.color=`black`'
onclick='this.onmouseover=null; this.onmouseout = null;'>
hello
</div>

<br>

<div id='div2'
onclick="div1 = document.getElementById(`div1`); div1.style.color=`blue`; div1.onmouseover = 'this.style.color=`yellow`';">
world
</div>

div2's onclick handler is working when I try to change another element of div1 (e.g. div1.style.color='blue'), and div1's onclick handler is successfully changing the onmouseover function for itself (e.g. onclick='this.onmouseover=null; this.onmouseout = null;).

But the div2 onclick handler won't change the onmouseover function for div1. I've tried changing div1.onmouseover = "this.style.color='yellow'" to div1.onmouseover = "document.getElementById('div1').style.color='yellow'", but it still doesn't work.

Anyone know what's going on here?



Solution 1:[1]

A control variable can be used to drive the program. In this way, the necessary conditions for directing the program are checked. In the solution below, the old mouseover event of the first <div> element is fired unless the second <div> is clicked; After clicking the second <div>, the new mouseover event of the first <div> is fired.

const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');
let passive = false, newEventHandler = false;

/* old mouse over event */
div1.addEventListener('mouseover', function() {
  if(!passive && !newEventHandler) {
    this.style.color = "purple";
    console.log("old mouse over");
  }
});

/* new mouse over event */
div1.addEventListener('mouseover', function() {
  if(newEventHandler) {
    this.style.color = "yellow";
    console.log("new mouse over");
  }
});

/* passive mouse out event */
div1.addEventListener('mouseout', function() {
  if(!passive)
    this.style.color = "black";
});

/* conditions */
div1.addEventListener('click', function() {
  passive = true;
});

/* conditions */
div2.addEventListener('click', function() {
  div1.style.color = "blue";
  newEventHandler = true;
});
<div id='div1'>hello</div><br>
<div id='div2'>world</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1