Is there a way to trigger or redirect an event from one element to another in JavaScript without directly calling the event function? I am not looking for simply calling the event function, but rather want the browser to execute it with all UI effects that would normally occur if the event happened on the actual element. This is similar to how a <label>
element works for a checkbox.
For example, let's say there are two DIV elements - one with a :hover
CSS pseudo-class and the other without. If the mouse hovers over the second DIV, I want the browser to act as if the mouse is hovering over the first DIV, triggering the :hover
effect. However, I do not want to explicitly define a CSS class for this behavior; I want the browser to apply the existing CSS pseudo-classes.
Example:
CSS
#div1 {
background: green;
}
#div1:hover {
background: red;
}
#div2 {
width: 100px;
height: 100px;
position: absolute;
bottom: 0;
right: 0;
background: blue;
}
HTML
<div id="div1">Hello</div>
<div id="div2">world</div>
No jQuery, only plain vanilla JavaScript.
Edit:
Using dispatchEvent
does not trigger the UI (CSS pseudo-classes like :hover
). Here is an example (sorry for the one-liner):
<div id="div2" onmouseover="var e=document.getElementById('div1'); var evt = new MouseEvent('mouseover', {'view': window,'bubbles': true,'cancelable': true}); e.dispatchEvent(evt);">world</div>