Raj
Raj

Reputation: 370

Repeating a Click Event in jQuery Without Removing The Previous Click Effect

$(document).ready(function() {
		  $('img').click(function(e) {
			    var offset = $(this).offset();
			    /*alert("X: " + (e.pageX - offset.left) + " / Y: " + (e.pageY - offset.top));*/
			    $(this).after('<h3 class="label">Label</h3>');

			    $('.label').offset({ top: e.pageY - offset.top, left: e.pageX - offset.left });

		  });
		});
.label {
	position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

	<img src="http://mdikici.com/wp-content/uploads/2014/12/living-room-underlay-glossy-laminate-flooring-with-grey-microfiber-sleeper-sofa-and-nice-indoor-fireplace-in-amazing-minimalist-living-room-design-trendy-minimalist-living-room-design-ideas.jpg" alt="Living Room" title="Living Room" usemap="#tagarea" />

</body>

Thanks for helping me out.

Let me clarify what I am trying to achieve, I have an image of a living room with various objects (TV, Sofa, etc) and when I click on say the TV area I want to add a Image Label right next to it, now I have achieved this part but when I click again on any other area say if I clicked on the Sofa then the Image Label disappears from the TV area and shows near the Sofa area, so basically I want this functionality to loop and should be able to add multiple Image Labels.

Please check the script and kindly let me know how to fix it.

$(document).ready(function() {
      $('img').click(function(e) {
            var offset = $(this).offset();
            $(this).after('<img src="images/badge.png" alt="Badge" title="Badge" class="label" />');

            $('.label').offset({ top: e.pageY - offset.top, left: e.pageX - offset.left });

      });
    });

    <body><img src="images/living-room-1.jpg" alt="Living Room" title="Living Room" /></body>

Thanks

Upvotes: 1

Views: 110

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

The issue is because although you append a new img, your selector of .label is changing the position of all img elements - even those previously added. You need to amend your code to relate to only the new img element being added. Try this:

$('img').click(function(e) {
    var offset = $(this).offset();
    $('<img src="images/badge.png" alt="Badge" title="Badge" class="label" />')
        .insertAfter(this)
        .offset({ 
            top: e.pageY - offset.top, 
            left: e.pageX - offset.left 
        });
  });

UPDATE

Given your updated HTML example and requirements, this should work for you:

$('img').click(function (e) {
    var offset = $(this).offset();
    $('<h3 class="label">Label</h3>')
        .insertAfter(this)
        .css({
            top: e.pageY - offset.top,
            left: e.pageX - offset.left
        });
});

Example fiddle

Upvotes: 1

Related Questions