Get clicked element using jQuery on event?

JqueryEvent HandlingClickJquery Events

Jquery Problem Overview


I'm using the following code to detect when a dynamically generated button is clicked.

$(document).on("click",".appDetails", function () {
    alert("test");
});

Normally, if you just did $('.appDetails').click() you could use $(this) to get the element that was clicked on. How would I accomplish this with the above code?

For instance:

$(document).on("click",".appDetails", function () {
    var clickedBtnID = ??????
    alert('you clicked on button #' + clickedBtnID);
});

Jquery Solutions


Solution 1 - Jquery

As simple as it can be

Use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});

Solution 2 - Jquery

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

Solution 3 - Jquery

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});

Solution 4 - Jquery

There are many ways you can do that

>>The first method is by using the javascript target

$(document).on("click",".appDetails", function (event) {
    var clickebtn = target.event.id;
});

Solution 5 - Jquery

$(".masonry__img").click((e) => {
      console.log(e.currentTarget.currentSrc);
});

This will add an onClick handler to each image with the class masonry__img.

Solution 6 - Jquery

A simple way is to pass the data attribute to your HTML tag.

Example:

<div data-id='tagid' class="clickElem"></div>

<script>
$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('data');
   alert('you clicked on button #' + clickedBtnID);
});
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTHE JOATMONView Question on Stackoverflow
Solution 1 - JquerybipenView Answer on Stackoverflow
Solution 2 - JqueryBastian RangView Answer on Stackoverflow
Solution 3 - JquerywaffleauView Answer on Stackoverflow
Solution 4 - JqueryiamnonsoView Answer on Stackoverflow
Solution 5 - JqueryjpeggtulsaView Answer on Stackoverflow
Solution 6 - JqueryiamnonsoView Answer on Stackoverflow