Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger event for UI indirectly

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>

1 Answers

Now I'm pretty sure you want to dispatch a event in JavaScript.

It's pretty simple. You can dispatch a event by using this.

elem.dispatchEvent(event);

where elem is the target element.

You can have a look at Mozilla docs.

This is a code snippet I copied from the Mozilla docs. It dispatches a MouseClick Event.

function simulateClick() {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.getElementById('checkbox'); 
  var cancelled = !cb.dispatchEvent(event);
  if (cancelled) {
    // A handler called preventDefault.
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault.
    alert("not cancelled");
  }
}

and this is for MouseOver event.

object.addEventListener("mouseover", myScript);

Check out W3CSchool doc.

like image 189
Prajwal Avatar answered Jun 07 '26 08:06

Prajwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!