Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Javascript - Prepend Element when event listener trigger mouse enter

I would like to get some advise from you guys, how can I prepend html element when the event listener listen I mouse enter to the container area. I am using ReactJS to build my frontend. I encounter an issue as I cannot prepend the html element by using the event target which is provided by the callback of the event listener. I have included my code snippet as below:

box.addEventListener("mouseleave", function (evt) {
        evt.target.style.border = "unset";
      });
      box.addEventListener("mouseenter", function (evt) {
        evt.target.style.border = "1px solid red";
        var div = document.createElement("div");
        div.style.backgroundColor = "red";
        div.style.height = "10px";
        div.style.width = "10px";
        evt.target.parentNode.insertBefore(evt.target,div);
      });

In fact, I would like to prepend below div to the container parent whenever I mouseenter the div container. enter image description here

I really appreciate your contribution.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Unfortunately they way you are trying is not the react way.

You need to use state and if statements in your code with React way.

Here is a sample for you:

https://codesandbox.io/s/distracted-tree-1fpjnr

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [isShowDiv, setIsShowDiv] = useState(false);
  return (
    <div
      className="App"
      onMouseLeave={() => setIsShowDiv(false)}
      onMouseEnter={() => setIsShowDiv(true)}
    >
      {isShowDiv && (
        <div style={{ background: "red", height: "50px", width: "100%" }}></div>
      )}
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!