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');
});
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');
});
Share
Improve this question
edited Jan 3, 2009 at 12:49
nickf
546k198 gold badges658 silver badges726 bronze badges
asked Dec 24, 2008 at 22:14
adamadam
4314 gold badges6 silver badges15 bronze badges
2
- I'd like to see the HTML involved to ensure the CSS selector is accurate. – Samir Talwar Commented Dec 24, 2008 at 22:23
- have you tried this docs.jquery.com/Effects/hide ?? you can use the 'img.flickr_photo as selector. – Perpetualcoder Commented Dec 24, 2008 at 22:48
3 Answers
Reset to default 18This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});
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');
});
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.