1

I have this code which adds markers on a jpg map dynamically based on where you click on the map image. It creates the ids dynamically as well. I am trying to attach a click event to every dynamically created marker so that if the user clicks on the marker it will be deleted. The problem is that when they click on the marker it generates another marker. I want the user to be able to place the marker on the map by clicking on the map and then if they want to delete the marker they can click on it again without generating a new marker when they click on the marker they want to delete.

Thank you in advance for all your help.

JS :

$(document).ready(function(){
    var clicks = 0;
    $("#container").click(function(e) {
        e.preventDefault();
        var x = e.pageX - 38;
        var y = e.pageY - 60;
        var img = $('<img>');
        img.css('top', y);
        img.css('left', x);
        img.css('width',60);
        img.css('height',60);
        img.attr('src', 'images/location-marker1.png');
        img.attr('id', 'marker' + clicks);
        img.attr('class', 'marker' + clicks);
        img.appendTo('#container');

        $("#container").on("click", "img.marker" + clicks, function(){
            var id = $(this).attr('id');
            alert(id);
            $(this).remove();
        });
        clicks += 1;
    })
});

HTML :

<div id="container">
    <img src="images/floorplan1_fs.jpg">
</div>
4
  • 1
    Ooooh, nesting event handlers in another are generally a bad idea. Commented Dec 7, 2016 at 21:53
  • do you want jquery, that would be easier Commented Dec 7, 2016 at 21:53
  • 1
    Your click event will propagate up from the img to the container. Try adding an event argument to your img click handler and calling event.stopPropagation() ... developer.mozilla.org/en/docs/Web/API/Event/stopPropagation Commented Dec 7, 2016 at 21:57
  • Sorry I didn't get a chance to look at this until this morning. Thanks Terry I am a bit of a beginner when it comes to Javascript. Yes I know a little JQuery as well. I will try your suggestion George Commented Dec 8, 2016 at 14:50

2 Answers 2

2

Actually, all you need to do is to (1) use a common class, say marker, to identify inserted markers, and (2) move the event listener out of the outer click function, and let it stand on its own right:

$("#container").on("click", "img.marker", function(e) {
    $(this).remove();
    e.stopPropagation();
});

This not only greatly simplifies your script, as #container will now listen to click events emitted by all dynamically added img.marker elements, but the use of e.stopPropagation stops the click event from bubbling up to the parent, which causes a new child to be added when you click to remove one.

Here is a proof-of-concept example, with some minor changes to your base code:

  1. There is no longer any need to track unique IDs
  2. Here we take advantage of the amazing chaining capabilities imparted by jQuery

$(document).ready(function() {
  $("#container").click(function(e) {
    
    e.preventDefault();
    
    var x = e.pageX - 38,
        y = e.pageY - 60,
        $img = $('<img>');
    
    $img
      .css({
        top: y,
        left: x,
        width: 60,
        height: 60
      })
      .attr({
        src: 'https://placehold.it/60x60'
      })
      .addClass('marker')
      .appendTo('#container');
  });

  $("#container").on("click", "img.marker", function(e) {
    $(this).remove();
    e.stopPropagation();
  });
});
#container {
  position: relative;
}
#container .marker {
  box-shadow: 0 0 10px 10px rgba(0, 0, 0, .5);
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <img src="https://placehold.it/500x500">
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

Just use a general class to attach the event and put it outside of the other click event :

$(document).ready(function(){
    var clicks = 0;
    $("#container").click(function(e) {
        e.preventDefault();
        var x = e.pageX - 38;
        var y = e.pageY - 60;
        var img = $('<img>');
        img.css('top', y);
        img.css('left', x);
        img.css('width',60);
        img.css('height',60);
        img.attr('src', 'images/location-marker1.png');
        img.attr('id', 'marker' + clicks);
        img.attr('class', 'marker');
        img.appendTo('#container');

        clicks += 1;
    })
    $("#container").on("click", "img.marker", function(){
      var id = $(this).attr('id');
      alert(id);
      $(this).remove();
      e.stopPropagation();
    });
});

NOTE : If you want to improve the code you could use :

$('<img />', {  
    'class' : "marker",
    src     : 'images/location-marker1.png',
    css     : {
        top    : y,  
        left   : x, 
        width  : 60, 
        height : 60, 
    },
    on : {
        click: function() {
             $(this).remove();
        }
    }
}).appendTo('#container');

Hope this helps.

$(document).ready(function(){
  $("#container").click(function(e) {
    e.preventDefault();

    $('<img />', {  
      'class' : 'marker',
      src     : 'https://www.gobages.com/wp-content/uploads/2015/09/marker-reservoirs.png',
      css     : {
        top    : e.pageY - 37,  
        left   : e.pageX - 24, 
        width  : 30, 
        height : 30, 
      },
      on : {
        click: function(e) {
          e.stopPropagation();
          $(this).remove();
        }
      }
    }).appendTo('#container');
  });
});
#container {
  position: relative;
}
#container .marker {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <img src="http://geology.com/world/world-map-clickable.gif">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.