Cole
Cole

Reputation: 459

Append a tag box inside an image after clicking on it

I'm trying to make a photo tag plugin for my website. I have long way to go. I know there are other actual plugins but I want to create my own here. The question is I was trying to make a box appear on a image after clicking it, it is not appearing, it is not appending on the image.

<head>
    <style>
    #imageHolder {
        position:relative;
        border:dashed 2px #7E7E7E;
        min-width:300px;
        min-height:300px;
        box-shadow:0 0 5px #000;
        cursor:pointer;
        float:left;
        }
        #tag
        {
          position:absolute;
          top:0;left:0;
          width:250px;
        }
        #box
        {
          border:solid 3px #000;
          width:100px;
          height:100px;
          float:left;
        }
    </style>

    <script style = "text/javascript"> 
      $(document).ready(function(){
        var mouseX = 0;
        var mouseY = 0;
        $("#imageHolder img").click(function(e){
          var imgBox = $(this).parent();
          mouseX = e.pageX - $(imgBox).offset().left;
          mouseY = e.pageY - $(imgBox).offset().top;
          $('#tag').remove();
          $(imgBox).append('<div id = "tag"><div id="box"></div></div>');
          $('#tag').css({top:mouseY,left:mouseX});
        });
    });
    </script> 
    </head>

<body>
<div id = "imageHolder">
<img src = "test.jpg"/>
</div>
</body>

What is the problem with this code?

Upvotes: 1

Views: 1536

Answers (2)

Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

Interesting and difficult yet very simple solution

http://jsfiddle.net/e4tr7/5/

$("#imageHolder img").click(function (e) {
  var offset = $(this).offset();
  var position = {
    left: e.clientX - offset.left - 50,
    top: e.clientY - offset.top - 50
  }
  var append = $('<div class="tag"><div class="box"></div></div>').draggable({containment: "parent"}).css({"position":"absolute","top":position.top,"left":position.left});
  $(this).parent().append(append);

});

Upvotes: 2

Olaf Dietsche
Olaf Dietsche

Reputation: 74118

Your example seems to work, see JSFiddle.

I moved the click function to the div, since the test.jpg image is not available. I also colored the divs to show it more clearly. Otherwise I left the rest of your code as is

$("#imageHolder").click(function(e){
  var imgBox = $(this);

Upvotes: 0

Related Questions