Reputation: 2024
I have a set of divs. They need to be olive when i hover and they need to stay red when clicked (They need to go back to white when red divs are clicked). I need to make the divs "selected" (introduce a new class called selected) when they are clicked.
The problem is that everything works fine but when i hover on a div just after it gets clicked, the hover still seems to have effect. Here's my code
$(document).ready(function () {
$("div.onemovie").not("select").hover(
function () {
$(this).css("background-color", "Olive");
},
function () {
$(this).css("background-color", "White");
}
);
});
Click Code:
$(document).ready(function () {
$("div.onemovie").toggle(
function () {
$(this).toggleClass("select");
$(this).css("background-color", "Red");
},
function () {
$(this).toggleClass("select");
$(this).css("background-color", "White");
}
);
});
Here's a JS Fiddle link of my situation: http://jsfiddle.net/mNsfL/
Upvotes: 0
Views: 1099
Reputation: 43168
Does this version do what you want?
I think you can accomplish what you want much more simply by using CSS for the hover effect.
Also, you shouldn't have to set the background color back to white. When the rule no longer applies, the div
will revert to its former settings.
Upvotes: 2
Reputation: 9691
$("div.onemovie").bind('click', function(){
$(this).css("background-color", "White");
})
.bind('mouseover', function() {
$(this).css("background-color", "Red");
})
It's ok to listen to each of the events and handle them separately.
Upvotes: 1
Reputation: 17061
The best way I can see to do this would be to bind each of the events and make it so that, during the mouseover event, if the div
is clicked, the mouseout event gets unbinded.
This will make it so that the mouseout code doesn't execute, making the div
retain the color change.
If you are using jQuery 1.7+, you should use on()
to bind the events and off()
to unbind them.
Upvotes: 1