jQuery event currentTarget dataset

Dol picture Dol · Sep 2, 2014 · Viewed 8.6k times · Source

In every jQuery event jQuery provides the currentTarget which is the same as this, but as far as I understand the properties of currentTarget depend on your browser.

In chrome I can get event.currentTarget.dataset which gives me the data from the element that started the event but I don’t think this works in all browsers. The only cross browser solution that I know of is to get the data by wrapping the currentTarget in another jQuery object like below.

var div = jQuery("<div/>").data("numbers", [1,2,3]);
div.click(function(e) {
  var data = jQuery(e.currentTarget).data();
  console.log(data.numbers);
});

Does anyone know a cross browser solution to get the data without creating a new jQuery object with this/currentTarget?

Update: Just to be clear and the reason I ask:

We are converting the element that triggered the event into a jQuery object again, sending it through jQuery a second time (it was already a jQuery object to create the event). I'm hoping for a way to carry the already created jQuery object into the event. Slides 44 & 45 on this presentation explain my thought process.

You can do this with event.currentTarget.dataset but I don't think its a cross browser solution. In the code above you could use the cached jQuery object div to get the data without recreating a jQuery object. That works for that specific example, but what would you do with a dynamic event like the delegate event below:

jQuery("#container").on('click', '.pop-data', function(e) {
  var data = jQuery(e.currentTarget).data();
  alert(data);
});

The code above works and is not a bad solution but does anyone know a way to get the data without creating a new jQuery object?

Answer

Blamkin86 picture Blamkin86 · Mar 18, 2015

Look down at the accepted answer for

Having problems in IE8 when attempting to get data from target event

jQuery("#container").on('click', '.pop-data', function(e) {
  console.log($(e.target).attr('data-numbers'));
});

Personally, I couldn't get the .data() jQuery stuff to work (not sure why) but the above works with sticking the HTML attribute in-line.

<img src='...' data-numbers='1'>