Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: hover when focus on other element

If you look at the following CSS:

fieldset#searchform input[type=submit]:hover
{
    background-position: center -13px;
}
fieldset#searchform input[type=text]:focus fieldset#searchform input[type=submit]
{
    background-position: center -26px;
}
fieldset#searchform input[type=text]:focus fieldset#searchform input[type=submit]:hover
{
    background-position: center -39px;
}

The idea is that a button can be hovered and changed the background, but if the input field has user focus then the button will have a different background when hovered and inactive. However this does not work because CSS doesn't support it! How can I get this to work? jQuery perhaps?

EDIT: I am NOT trying to do multiple definitions!

like image 803
Cameron Avatar asked Jun 26 '26 17:06

Cameron


2 Answers

Yeah, that's definitely not how CSS works so you'll need to use JS. Try something like this:

Generic JS:

$("fieldset#searchform :text")
    .focus(function(){ $("fieldset#searchform :submit").addClass("focus"); })
    .blur(function(){ $("fieldset#searchform :submit").removeClass("focus"); });

Generic CSS:

fieldset#searchform input[type=submit]:hover {
    background-position: 50% -13px;
}
fieldset#searchform input[type=submit].focus {
    background-position: 50% -26px;
}
fieldset#searchform input[type=submit].focus:hover {
    background-position: 50% -39px;
}

Demo: jsfiddle.net/Marcel/pHsxa

like image 191
Marcel Avatar answered Jun 29 '26 12:06

Marcel


Yes, jQuery, or even plain javascript will do:

With jQuery, use focus() and blur(). In my example, I just change the submit class when these events occurred. I changed the background-color, but you could do anything of course.

http://jsfiddle.net/jtbowden/WPdxE/

The code (simplified):

$(':text').focus(function() {
    $(':submit').addClass('focus');
});

$(':text').blur(function() {
    $(':submit').removeClass('focus');
});
like image 37
Jeff B Avatar answered Jun 29 '26 11:06

Jeff B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!