How to put symbol or text into an image's clicked position

Viewed 118

I am trying to implement something like this, a predefined symbol or text should be putted on a image where clicked. Suppose there is an image and I had clicked on the top right corner of that image. Now I want to show something on that clicked position. I can get the coordinate of the clicked position. But I am not getting how I can put something on that place using this coordinate. This is what I had tried.

HTML code :

<img src="result.png" alt="" id="image">

JS code:

$('#image').click(function (e) { 
var posX = $(this).position().left,
    posY = $(this).position().top,
    positionX = e.pageX - posX,
    positionY = e.pageY - posY;
$("#image").html('<p id="clicked">Clicked here</p>');
});
2 Answers

You are trying to set the html of an image element that is clicked. You do nothing with the x and y position of the element.

You need to append an element and set the position.

$('#myDiv').on("click", "img", function (e) { 
  var wrapper = $(this).parent(),
    position = wrapper.offset(), 
    posX = position.left,
    posY = position.top,
    positionX = Math.floor(e.pageX - posX),
    positionY = Math.floor(e.pageY - posY),
    marker = $('<p class="clicked">Clicked here</p>');
  marker.css({top: positionY + "px", left: positionX + "px"})
  wrapper.append(marker);
});
#myDiv {
  position: relative;
  border: 1px solid green;
}

#myDiv p {
  position: absolute;
  color: rgb(0, 255, 255);
  mix-blend-mode: difference;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Example</h1>
<div id="myDiv">
  <img src="http://placekitten.com/g/400/300" alt="">
</div>

Consider an alternative solution.

$(function() {
  $.fn.setMarker = function(e, o) {
    if (o == undefined) {
      o = $("<p>", {
        class: "clicked"
      }).html("Clicked Here");
    }
    var self = $(this);
    var marker = o.appendTo(self.parent()).css({
      top: (e.pageY - self.offset().top) + "px",
      left: (e.pageX - self.offset().left) + "px"
    });
  }

  $('#myDiv-1').on("click", "img", function(e) {
    $(this).setMarker(e);
  });
});
#myDiv-1 {
  position: relative;
  border: 1px solid green;
}

#myDiv-1 p {
  position: absolute;
  color: rgb(0, 255, 255);
  mix-blend-mode: difference;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Example</h1>
<div id="myDiv-1">
  <img src="http://placekitten.com/g/400/300" alt="">
</div>

This adds the function as a jQuery extension basically. If you like, you can modify the function to pass in an jQuery Object or Element to add as the marker.

Related