Reputation: 81
I want to make a picture in black and white when you hover it or click on it. It has to stay in black and white until you hover or click on another picture. That's why I decided to add a class .selected to the div with a class .in - so that an image might become in black and white(using grayscale(100%))
It works perfectly with simple goal:hover in css, but when I use jQuery's addClass(), nothing seems to work! Why? and what is the best way to accomplish it? Here is my html where I add my images:
@foreach (var image in Model.ProductImages)
{
<div class="in goal pic">
<img src="~/Content/Images/apple.jpg" alt="test"/>
</div>
}
Here are my css styles:
.in {
text-align: center;
}
.goal {
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
}
.selected {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
.pic {
border: 2px solid #fff;
float: left;
height: 100px;
width: 100px;
margin: 20px;
overflow: hidden;
-webkit-box-shadow: 5px 5px 5px #111;
box-shadow: 5px 5px 5px #111;
}
And here is my script
$(document).ready(function () {
$(".in").hover(function () {
$(".in").removeClass('selected');
$(this).addClass("selected");
});
});
Upvotes: 0
Views: 62
Reputation: 13211
Well 1. the selector should be .in img
and you also have to support the out
event. Regarding to the documentation of jquery https://api.jquery.com/hover/
$('.in img').hover(
function() { $(this).addClass('selected') },
function() { $(this).removeClass('selected') },
)
Upvotes: 1
Reputation: 36703
You are adding class selected
to div and not to the image. To make it work you need to change you selector in CSS.
.selected img {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
}
Upvotes: 1