Jquery: Hover/unhover combined with blur/focus
25,796
Solution 1
Update : don't use jQuery.
Plain CSS solution :
<input type="text" value="Test Element" id="test"/>
<style>
#test:hover, #test:focus { color: blue; }
</style>
jsFiddle demo here : https://jsfiddle.net/ngkybcvz/
Using different CSS classes could be a solution.
.elementHovered { color : blue; }
.elementFocused { color : blue; }
<input type="text" value="Test Element" id="test"/>
$("#test").hover(function() {
$(this).addClass("elementHovered");
}, function() {
$(this).removeClass("elementHovered");
});
$("#test").focus(function() {
$(this).addClass("elementFocused");
});
$("#test").blur(function() {
$(this).removeClass("elementFocused");
});
jsFiddle demo here : http://jsfiddle.net/ZRADe/
Solution 2
Depends what elements you want to use, if you are doing it for inputs, I recommend using a focusin, focusout instead.
But it would look something like this.
$(document).ready(function() {
$("li").hover(
function () {
$(this).addClass('.blue');
},
function () {
$(this).removeClass('.blue');
}
);
$("li").click(function() {
$("li").removeClass('.blue');
$(this).addClass('.blue');
});
});
Author by
Admin
Updated on October 04, 2020Comments
-
Admin over 3 years
I've been looking through the questions, but i can't find exactly what i'm looking for..
I want to know how to make a function that does the following:
- If you hover an element the element changes to blue for example
- If you unhover it changes back to default
- If you click it (focus), it keeps the blue color from the hover effect even if you unhover it
- If you click away (blur), it goes back to the default color and the mouseover effect works again
How do I do so ;)?
-
Boldewyn about 13 yearsHm. You should put content in that fiddle, too.
-
Sylvain about 13 yearsWrong link copy / pasted. I've put the content here
-
Admin about 13 yearsI didn't think of the possibility to use two different classes for hover and focus, but this works great - thanks ;)