views:

787

answers:

4

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');
});
+18  A: 

This is what you need to do:

$('img.flickr_photo').click(function(){  
       $(this).css('border-color','#777');
});
Andreas Grech
Better answer. ++
Shog9
that worked, thanks!
adam
Mark the answer as 'Answered' if it helped you. Thanks.
Andreas Grech
+1  A: 

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.

Matthew Crumley
+3  A: 

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');
});
redsquare
A: 

You are passing the ID of a photo, which is 'photo239839'

$('#photo'+photo['id']); // so you get this: #photophoto239839

Instead of passing the ID of the photo you could pass the reference to that photo and avoid messing around with concatenation.

function (photoElem) {
  $(photoElem).click(function() {
    $(this).css('border-color','#777');
  });
}

You can also improve on this line: $(this).css('border-color','#777');
Move the inline style to the stylesheet and manipulate the class of a photo instead of inline style. Like this:

$(this).addClass("active");
$(this).removeClass("active");

It's easier to read and easier to maintain.

Alisey