lowe_22
lowe_22

Reputation: 395

Passing Event data to callback function with jQuery

I'm having difficulty understanding how to use event.data to return the value of whatever element the event fired one. Here my example:

<a href="#" class="dw_add">
  <img src="http://something" />
</a>

var callback = function(event){ console.log(event.data.src) }

$('.dw_add')
  .on('click', { src: $(this).find('img').attr('src') },callback);

$this is currently referencing the document and not the that was clicked. Hopefully you can see what I'm trying to do, but my javascript knowledge is limited, think I'm approaching it in a PHP mindset.

Any ideas how to pass the value of 'img src' to the callback?

Upvotes: 1

Views: 6453

Answers (3)

adeneo
adeneo

Reputation: 318312

You are not inside a functions scope, so this:

$('.dw_add').on('click', { src: $(this).find('img').attr('src') },callback);

will not work as $(this) is not the element you think it is because there is no local scope for the clicked element, no event.target or event.data etc!

However this will work as it has a direct reference to the element and scope for "this" is not an issue:

var callback = function(event){ console.log(event.data.src) }
var elm = $('.dw_add');
elm.on('click', { src: elm.find('img').attr('src') },callback);

and this will work as $(this) is inside a function scope:

function callback(a){ console.log(a) }

$('.dw_add').on('click', function() {
  var a = $(this).find('img').attr('src');
  callback(a);
});​

Also, using $(this) inside the callback function will work, as it is, again, inside a functions scope and has a reference to the targeted element.

Upvotes: 3

josh3736
josh3736

Reputation: 145012

In jQuery event handlers, this is set to the DOM element that fired the event. Since you're attaching an event handler to the <a> element, this will be the link.

If you want to get the src of the img, you'll have to find the img element in the triggering a by using find() or children():

$('.dw_add').on('click', function(e) {
    $(this).children('img').attr('src');
});

Upvotes: 0

Matt Bradley
Matt Bradley

Reputation: 4505

Why not do something like this:

var callback = function(event){ console.log($(this).find('img').attr('src')) }

$('.dw_add')
    .on('click', callback);

Upvotes: 1

Related Questions