linuxoid
linuxoid

Reputation: 1447

jQuery click fires but no event passed

I have this:

<div id="pic_pin">
    <div id="selected_picture">
        <img src="map.png" />
    </div>
</div>

I add a marker picture on clicking the map image:

$('#selected_picture').on('click', function(e){
    offset = $('#selected_picture').offset();
    x = e.pageX - offset.left - 25;
    y = e.pageY - offset.top - 25;
    var pin = $('<div class="pin"><img class="pin-img" data-left="' + x + '" data-top="' + y + '" src="pin.png" /></div>');
    pin.uniqueId();
    $('#pic_pin').append(pin);
    pin.css('left', x).css('top', y).show();
});

Then on clicking the marker image (div) I want to open a pop-up:

$('#pic_pin').on('click', '.pin', function(e){
    console.log('log: '+e.target.id);
    ...
});

And the problem is the e.target.id is empty - it simply shows 'log: ', no id is shown. Why?

Upvotes: 2

Views: 77

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

I'm assuming that the pin.uniqueId() function call provides the .pin elements with id attributes, as they do not have them by default.

Assuming that's the case you need to use this or e.currentTarget, not e.target.

When using a delegated event handler target is the element which the event has bubbled to (#pic_pin in your case), whereas this and currentTarget refer to the element which raised the event.

Try this:

$.fn.uniqueId = function() {
  $(this).prop('id', new Date().getTime());
}

$('#selected_picture').on('click', function(e) {
  offset = $('#selected_picture').offset();
  x = e.pageX - offset.left - 25;
  y = e.pageY - offset.top - 25;
  var pin = $('<div class="pin"><img class="pin-img" data-left="' + x + '" data-top="' + y + '" src="pin.png" /></div>');
  pin.uniqueId();
  $('#pic_pin').append(pin);
  pin.css('left', x).css('top', y).show();
});

$('#pic_pin').on('click', '.pin', function(e) {
  console.log('log: ' + e.currentTarget.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pic_pin">
  <div id="selected_picture">
    <img src="map.png" />
  </div>
</div>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You need to use this.id or also $(this).attr('id') :

$('#pic_pin').on('click', '.pin', function(e){
    console.log('log: '+this.id);
    ...
});

When this inside the click context refer to the current clicked pin.

Upvotes: 1

Related Questions