Search code examples
jqueryfocushovermouseoverblur

Jquery: Hover/unhover combined with blur/focus


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:

  1. If you hover an element the element changes to blue for example
  2. If you unhover it changes back to default
  3. If you click it (focus), it keeps the blue color from the hover effect even if you unhover it
  4. If you click away (blur), it goes back to the default color and the mouseover effect works again

How do I do so ;)?


Solution

  • 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/