0

I want to place a dynamically created Html Span element wherever I click mouse. I thought to use coordinate obtained from click but it didn't work.

Html:

 <div id = "test" style="background:#7FFFD4; width:1000px; margin:20px; height:20px; position: relative;">
  Area For Test
 </div>

Script

 $(document).ready(function () {

    $("#test").click(function (e) {
         $('#test').append('<span id = "abc">' + 'sampleText' + '</span>');
         var x = Math.round(e.pageX - posX) + "px";
         var y = Math.round(e.pageY - posY)+ "px";
         $('#abc').css({ 'position': 'absolute', 'top': x, 'left': y});

   });

});

So Is there a nice way to position Span Element where i click.

3 Answers3

1

I modified your snippet a little. Please find it here(https://jsfiddle.net/sdilipsam/7x47ejce/).

You can read more about clientX/Y vs Page X/Y in What is the difference between screenX/Y, clientX/Y and pageX/Y?

<div id="test">Area For Test</div>

$(document).ready(function () {

$("#test").click(function (e) {
    $('.float-span').remove();
    $('body').append('<span id = "abc" class="float-span">' + 'sampleText' + '</span>');
    var x = Math.round(e.clientX) + "px";
    var y = Math.round(e.clientY) + "px";
    $('.float-span').css({
        'top': y,
        'left': x
    });

});

});

#test {
    background:#7FFFD4;
    width:500px;
    height:500px;
    margin:20px;
    position: relative;
}
.float-span {
   position:absolute;
}
Community
  • 1
  • 1
SamD
  • 120
  • 1
  • 10
0

Swapping x and y to left and top, fixes most problems. Also you can remove the added span before the next one is being added.

 $(document).ready(function() {
   $("#test").click(function(e) {
     $('#abc').remove();
     $('body').append('<span id="abc">' + 'sampleText' + '</span>');
     var x = Math.round(e.pageX) + "px";
     var y = (Math.round(e.pageY) + 3) + "px";
     $('#abc').css({
       'position': 'absolute',
       'top': y,
       'left': x
     });
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" style="background:#7FFFD4; width:1000px; margin:20px; height:20px; position: relative;">
  Area For Test
</div>
rrk
  • 15,677
  • 4
  • 29
  • 45
0

top corresponds to Y-axis. Also remove appended span before creating a new one. Try this: Working fiddle here: http://jsfiddle.net/eu7xb4eL/

$(document).ready(function () {

    $("#test").click(function (e) {

        $('#abc').remove();

        var x = Math.round(e.pageX) + "px";
        var y = Math.round(e.pageY) + "px";

        $('<span id = "abc">' + 'sampleText' + '</span>').css({
            'position': 'absolute',
            'top': y,
            'left': x
        }).appendTo('#test');

    });

});
Victor Levin
  • 1,167
  • 6
  • 11