JQuery: hover / unhover combined with blur / focus

I looked through the questions, but I can not find what I am looking for.

I want to know how to make a function that does the following:

  • If you hover over an element, the element, for example, changes in blue.
  • If you cancel it, by default
  • If you click on it (focus), it will be blue from the hover effect, even if you open it
  • If you click (blur), it will revert to the default color and the mouseover effect works again.

How to do it?)?

+5
source share
6 answers

Using different CSS classes can 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 : http://jsfiddle.net/ZRADe/

+8

, , , focusin, focusout.

.

$(document).ready(function() {
    $("li").hover(
    function () {
        $(this).addClass('.blue');
    }, 
    function () {
        $(this).removeClass('.blue');
    }
    );

    $("li").click(function() {
        $("li").removeClass('.blue');
        $(this).addClass('.blue');
    });

});
+1

, , .

hover , . , unhover , , ...

JAVERY HOVER:

http://api.jquery.com/hover/

0

3 . 1 + 2 CSS hover

3 JQuery

$('#MyElement').removeClass('RegularClass');
$('#MyElement').addClass('SelectedClass');

4- , JQuery focusout, , .

0

1 and 2: use CSS.

like:

In CSS (blur is a base class):

.blurry{background:red;}
.blurry:hover{background:blue;}
.focused{background:blue;}

IN js:

$(document).ready(function() {
    $('#elementID').focus($(this).addClass('focused').removeClass('blurry');)
    });)
    $('#elementID').blur($(this).addClass('blurry').removeClass('focused');)
});

CSS will track mouseover / mouseout events without having to interact with the DOM. And js does the rest :)

0
source

I tried to do something very similar to a div, and this is what worked best for me:

var focusColor = "#008BFF";
var hoverColor = "#6FBEFF";

var clicked = false;

elem.focusin(
   function () {
       clicked = true;
       elem.css({ "border-color": focusColor });
   }
);

elem.focusout(
   function () {
       clicked = false;
       elem.css({ "border-color": "" });
   }
);

elem.hover(
   function () {
       if (clicked) {
           elem.css({ "border-color": focusColor });
       }
       else {
           elem.css({ "border-color": hoverColor });
       }
   },
   function () {
       if (clicked) {
           elem.css({ "border-color": focusColor });
       }
       else {
           elem.css({ "border-color": "" });
       }
   }
);
0
source

All Articles