Reputation: 431
I'm trying to change the border color of an image using its id with jquery ( photo['id'] is passed in from a previous function ) the ids of the photos are of the form 'photo239839'
$('#photo'+photo['id']+'').click(function(){
$('#photo'+photo['id']+'').css('border-color','#777');
});
When I try to use this same code using its class it works, but I can't use this method since there are multiple images on the same page with the same class
$('img.flickr_photo').click(function() {
$("this.flickr_photo").css('border-color','#777');
});
Upvotes: 2
Views: 2256
Reputation: 107950
This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});
Upvotes: 18
Reputation: 78667
I would always always add a css class rather than an inline style. Much more maintainable and extensible.
Example:
$('img.flickr_photo').click(function(){
$(this).addClass('greyishBorder');
});
Upvotes: 4
Reputation: 102725
Either photo['id'] is wrong, or is changing after you set up the click handler.
To test for the first case, you can alert (or console.log with FireBug, or whatever) the length of the jQuery selection:
alert($('#photo'+photo['id']).length);
The solution in the second case is to use 'this'. In the click handler, 'this' is set to the element that caused the click event.
$('#photo'+photo['id']).click(function(){
$(this).css('border-color','#777');
});
Edit: @Dreas Grech is right, as long as you want to apply the behavior to all the elements with the flickr_photo class. If you can generalize the selector to select all the elements with a single query, it's better to do that.
Upvotes: 1