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

105
Views
problem with using Element.remove function in js

I used js code from web to create dragable element, it should appear when i press ctrl key and it worked. But then i wanted to add function to delate it when i relase ctrl key.

And now its only create multiple elements when i keep pushing ctrl key and doing nothing when i relase it.

Please help, i dont know what im doing wrong :(

Ok i edited code, hope now its looks better. Sorry im noob in programming, im just starting soo thats why my code looks like crap :(

For now i deleted function for Element.prototype.remove() becouse its not working anyway. My question is how add it to this code. How make it working when i relese ctrl key.

I also discovered that code works not only with ctrl key, but with any key. Also when im keep pushing any key it keeps spawning same object again and again

window.addEventListener("keydown", function(e) {
  if (e.ctrlKey)
    var mousePosition;
    var offset = [0, 0];
    var div;
    var isDown = false;

    div = document.createElement("div");
    div.style.position = "absolute";
    div.style.left = "-100px";
    div.style.top = "-100px";
    div.style.width = "200px";
    div.style.height = "200px";
    div.style.background = "rgba(255, 0, 0, 0.4)";
    div.style.color = "black";

    document.body.appendChild(div);

    div.addEventListener("mousedown",function(e) {
      isDown = true;
      offset = [div.offsetLeft - e.clientX, div.offsetTop - e.clientY];
    },
    true
  );

document.addEventListener( "mouseup",function() {
      isDown = false;
    },
    true
  );

document.addEventListener("mousemove",function(event) {
      event.preventDefault();
        if (isDown) {
          mousePosition = {
            x: event.clientX,
            y: event.clientY,
            };
        
          div.style.left = mousePosition.x + offset[0] + "px";
          div.style.top = mousePosition.y + offset[1] + "px";

          moveX = mousePosition.x + offset[0] + "px";
          moveY = mousePosition.y + offset[1] + "px";

      }
    },
    true
  );
});

about 4 years ago · Juan Pablo Isaza
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!