I'm looking for a way to trigger / "redirect" an event from one element to another. How can this be done or is it possible at all? To be clear: I'm not searching for a way to directly call an event function, instead I want the browser to execute it itself with all UI aftereffects which would normally occur if a mouse event would happen directly on the actual element. Similar to the behaviour of an <label>
element for a checkbox.
Example: I have a DIV with a :hover
CSS pseudo-class and I have a second DIV. Both DIVs are not nested. If the mouse is hovered over the second DIV, I want the browser to act like the mouse is hovered over the first DIV, so it would load the :hover
CSS pseudo-class for it of the first DIV. But I don't want to create an explicit CSS name for it - I want the browser to use :hover
and other 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, please. Only plain vanilla JavaScript.
Edit:
Using dispatchEvent
doesn't trigger the UI (CSS pseudo-classes, like :hover
). Example (sorry for 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>