0

I use event.target.id several times on a page, but in one particular case it just doesn't work. It seems to return either null or an empty string.

$(document).ready(function() {
  var $modal = $('body');
  var $imgID = 'idcodeoftheimage';

  var $after2 = '<div class="w3-bar w3-bottom w3-center buttonbar"><div class="buttons"><a href="javascript:;" id="' + $imgID + '" class="flag"><i class="">Flag</i></a></div></div>';
  $modal.append($after2);

  $('body').on('click', '.flag', function(event) {
    var $id = event.target.id;
    console.log($id);
  });
});
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
</body>

</html>

The exact same line of code works elsewhere so I'm not sure what the issue is.

traxx2012
  • 394
  • 2
  • 16
  • 1
    Why are you giving the same ID to multiple elements? IDs should be unique. – Barmar Mar 03 '17 at 00:07
  • Can you turn the code in your question into an executable [Stack Snippet](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) so we can try it out? – Barmar Mar 03 '17 at 00:08
  • 1
    Javascript isn't PHP, you don't need to start variables with `$`. – Barmar Mar 03 '17 at 00:08
  • ...wait, you have `` elements inside those `` elements, and they don't have an ID. –  Mar 03 '17 at 00:10
  • @squint But the `` elements don't have `class="flag"` so they shouldn't matter. – Barmar Mar 03 '17 at 00:11
  • The page uses a lot of modals to display images in a lightbox-style. The IDs are equal to the filename; I use it for processing purposes. I just find it to be extremely manageble compared to a more conform solution using passing parameters and such. As far as I know, non-unique IDs are considered dirty but not explicitly wrong..? – traxx2012 Mar 03 '17 at 00:11
  • @Barmar: Doesn't matter. The `event.target` is the deepest element clicked. –  Mar 03 '17 at 00:12
  • @traxx2012 Instead of abusing IDs like that, use a `data` attribute. – Barmar Mar 03 '17 at 00:12
  • @squint So he should be using `event.currentTarget` instead? – Barmar Mar 03 '17 at 00:12
  • @Barmar: Yes, or `this`, assuming the `.flag` element is the one being targeted. This is almost certainly a duplicate. –  Mar 03 '17 at 00:13
  • The `event.currentTarget` was the solution. I didn't find the question mine is a duplicate of because I didn't search for the right terms since I didn't understand the problem well enough. Sorry for the duplicate and thanks for the help! – traxx2012 Mar 03 '17 at 00:27
  • Just FYI, you'll probably have much better luck using google to search for answers than StackOverflow's search tool, especially if you target `site:stackoverflow.com` specifically. My search term was [site:stackoverflow.com javascript id is blank](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+id+is+blank), which brought me to the duplicate. –  Mar 03 '17 at 00:29

0 Answers0