Question

I'm having some trouble pulling attributes from an event target element.

I am using php to access a mysql database. From the query I pull out some image file names and their respective id's. I then display these images in a table with the following line:

print '<td><img id="img_' . $row['paint_id'] . '" class="thumb_target" src="img/paint/thumb/' . $row['paint_thumb'] .'"></td>';

As you can see, this line gives each image the id 'img_xx' where xx is the images numeric id in the sql database. I also give each image the class 'thumb_target'. In document ready I set a .click event for the thumb_target elements. This makes an AJAX call which should pass the img_xx id as data. I got this to work in chrome using

data: 'imgID=' + event.target.id

However, several hours later I decided to check something else in firefox and found that it doesn't work for all browsers. Using jQuery's method:

var id = $(this).attr('id');

I can't get id to be anything but undefined. Am I targeting a different element than the element I think I am?

Here's the pertinent javascript:

function runClick() {
  var id = $(this).attr('id');
  alert(id);
  $.ajax({
    url: 'overlay.php',
    //~ data: 'imgID=' + event.target.id,
    //~ data: ({ imgID: id }),
    data: 'imgID=' + id,
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
        processJSON(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("Failed to perform AJAX call! textStatus: (" + textStatus +
              ") and errorThrown: (" + errorThrown + ")");
    }
  });
}

$(document).ready( function() {
  $('.thumb_target').click( function() {
    runClick();
  });

  $('#overlay').hide();
});

Here's a link to the test page: http://www.carlthomasedwards.com/painting2.php

Was it helpful?

Solution

runClick is executed in global scope, so this refers to the global object(window).

Use that instead:

$('.thumb_target').click( function(event) {
    runClick.apply(this);
  });

or even more simple:

$('.thumb_target').click( runClick);

OTHER TIPS

When the browser executes runClick, the this context isn't preserved. If you pause in the Chrome debugger, you can see that this is actually Window when runClick is called.

The way to bypass the problem is to pass the element into runClick:

function runClick(elem) {
  alert($(elem).attr('id'));
  ...
}

and

$('.thumb_target').click( function() {
  runClick(this);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top