How do I make a button draggable in html? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I make a button draggable in html? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I have this code:

<!DOCTYPE html>
<html>
    <script>
        score = 0
        function hi(buttonID){
            score += 1
            document.getElementById("label123").innerHTML = score
        }
    </script>
    <button onclick="hi(this)" id="Button123">
        <img src="button.png" alt="Button" width="100px" height="100px" draggable="true">
    </button>
    <label id="label123">Click it!</label>
    <h1> clicker.io </h1>
</html>

And I want to make the button (Button123) draggable. This will make it so that the user can experience the ability to move the button anywhere they want on the screen.

Answer

My old, laggy solution (min 4 FPS on firefox)

var btn = document.getElementById("btn");
function drag(e) {
  btn.style.left = `${e.pageX - 10}px`;
  btn.style.top = `${e.pageY - 10}px`;
}
btn.addEventListener("mousedown", () =>
  document.addEventListener("mousemove", drag)
);
btn.addEventListener("mouseup", () =>
  document.removeEventListener("mousemove", drag)
);
#btn {
  position: absolute;
}
<button id="btn">Button</button>

New solution using transform: translate() (min 40 FPS on firefox)

var btn = document.getElementById("btn");
function drag(e) {
  btn.style.transform = `translate(${e.pageX - 20}px, ${e.pageY - 20}px)`;
}
btn.addEventListener("mousedown", () =>
  document.addEventListener("mousemove", drag)
);
btn.addEventListener("mouseup", () =>
  document.removeEventListener("mousemove", drag)
);
<button id="btn">Button</button>
We are here to answer your question about How do I make a button draggable in html? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji