user3542456
user3542456

Reputation:

How to move an element to the mouse position

I'm trying to move an element when when the user clicks on the document, however, the element is moving to an offset position. How do I remove the offset when clicking? I'm trying to get the element to move to the exact position of the mouse, how do I do this? Would I need to use the .offset() function? If so, how would I do that?

HTML

Player Name:  <input type="text" name="name" id="name" /><br>
<button name="submt" id="meh">Submit</button>

JS

$(document).ready(function(){
    $(this).on("click", function(e){
        var x = e.pageX;
        var y = e.pageY;
        $("#meh").css("marginLeft", x);
        $("#meh").css("marginTop", y);
    })
})

Upvotes: 3

Views: 23053

Answers (3)

Malek Zarzour
Malek Zarzour

Reputation: 69

<div class="soccer-field">
<div class="ball"></div>
</div>

var container = document.querySelector(".soccer-field");
container.addEventListener('click', function (event) {
  var x = event.clientX;
  var y = event.clientY;
  var ball = document.querySelector(".ball");
  ball.style.position = "absolute";
  ball.style.left = `${x}px`;
  ball.style.top = `${y}px`;
})

Upvotes: 4

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85593

Use left and top instead, also ensure to use absolute or relative positioning:

$(document).ready(function(){
    $(this).on("click", function(e){
        var x = e.pageX;
        var y = e.pageY;
        $("#meh").css("left", x);
        $("#meh").css("top", y);
    })
})

Upvotes: 1

Shomz
Shomz

Reputation: 37711

It's probably much much easier to set its position absolutely and control it with left and top offsets instead of margins:

$(document).ready(function() {
  $(this).on("click", function(e) {
    var x = e.pageX;
    var y = e.pageY;
    var el = $("#meh");
    el.css('position', 'absolute');
    el.css("left", x);
    el.css("top", y);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Player Name:
<input type="text" name="name" id="name" />
<br>
<button name="submt" id="meh">Submit</button>

Otherwise, you'd need to calculate the offset based on the previous elements (because the button's offset will change after each click).

Upvotes: 3

Related Questions