tags:

views:

31

answers:

2

I have several images:

<img class="photo" src="{{ img.url_small }} />
<img class="photo" src="{{ img.url_small }} />
<img class="photo" src="{{ img.url_small }} />

I'm trying to change the border color when the user hovers over the image or clicks on it:

$(".photo").click(function() {
   $(".photo").css({"background":"white"});
   $(this).css({"background":"blue"});
});

$(".photo").mouseenter(function() {
   $(this).css({"background":"green"});
}).mouseleave(function() {
   $(this).css({"background":"white"});
});

(there is a white margin around each image thus that a change in background changes the border)

The trouble is when a user clicks on an image, it turns blue, but then when the mouse is moved from the image, the border turns white.

I tried some conditionals:

$(".photo").mouseenter(function() {
   if($(this).css("background") != "blue") {
      $(this).css({"background":"green"});
   }
}).mouseleave(function() {
   if($(this).css("background") != "blue") {
      $(this).css({"background":"white"});
   }
});

but the borders still turned back white from blue. How can I keep the border blue? Is there a more efficient way of doing this?

A: 

.hover is the more efficient way of doing mouseenter, mouseleave.

What you really need to do is when an image is clicked add a new class to it, like so:

$(".photo").click(function() {
   $(".photo").removeClass('currentImage');
   $(this).addClass('currentImage');
});

$(".photo").hover(function() {
     jQuery(this).addClass('hoverImage');
}, function() {
     jQuery(this).removeClass('hoverImage');
});

make sure that currentImage is styled like you want:

.currentImage {
background:blue;
}
.hoverImage {
background:green;
}
Anatoly G
That works quite well. That's a much better implementation. I also didn't realize you could assign two classes to the same element. One question, why do we need the "jQuery" part instead of just "$(this)"?
Ed
I use jQuery for some reason. I really don't know why. I think it was because at some point I had a library that used $ as well, and I was lazy, but it hung around :(
Anatoly G
also, YES, you can have as many classes as you want. Think of classes as TAGs for elements. It makes dealing with DOM way, WAY easier.
Anatoly G
+1  A: 

Don't use javascript for what you can do in CSS.

CSS will take care of the simple hover style change, then just add a class for the click.

If you need to support IE6 for the hover, I'd wrap the <img> in a <a> tag, and give that the background.

Live Example: http://jsbin.com/ogasa3

.photo {
    background:white;
}
.photo:hover {
    background:green;
}
.selected {
    background:blue;
}
.selected:hover {
    background:blue;
}

jQuery

$(".photo").click(function() {
    $(".photo.selected").removeClass('selected');
    $(this).addClass('selected');
});
patrick dw